您现在的位置是:主页>文章>反射的一个小例子 网站首页

反射的一个小例子

 很久没写博了,写了个反射的小例子。贴出来给大家看看

     static void Main(string[] args)
        {
       
            #Type的应用
            //----------Type的应用-----------//
            Type t = typeof(Test);
            Console.WriteLine(t.Name);
            var methods= t.GetMethods();
            var properties = t.GetProperties();
            var Fields = t.GetFields();
            Console.WriteLine("----------Fields.Length:" + Fields.Length + "-----------");
            foreach (var Field in Fields)
            {
                Console.WriteLine("字段名称:" + Field.Name);
            }
            Console.WriteLine("----------properties.Length:" + properties.Length + "-----------");
            foreach (var propertie in properties)
            {
                Console.WriteLine("属性名称:" + propertie.Name);
            }
            Console.WriteLine("----------methods.Length:" + methods.Length + "-----------");
            foreach (var method in methods) {
                if (method.Name == "Write") {
                  object o=  Activator.CreateInstance(t);
                    object[] parameters = new object[] { "This is test." };
                    method.Invoke(o,parameters);
                }
                Console.WriteLine("方法名称:"+method.Name);
                Console.WriteLine("返回类型:" + method.ReturnType);
                foreach (var Parameter in method.GetParameters())
                {
                    Console.WriteLine("方法参数列表的Type类型:" + Parameter.GetType());
                }
                Console.WriteLine();
            }
            //----------endType-----------//
            #endregion
        }
    #region 辅助类
    public class Test {
        public Test(List model){
            MyListClass = model;
        }
        public Test() { }
        public string testField;
        public string TestParameter { get; set; }
        private List MyListClass{get;set;}
        public List GetMyListClass()
        {
            if (MyListClass == null)
                return null;
            return MyListClass;
        }
        public void Write(string content)
        {
            File.AppendAllText(@"C:\Users\calvin\Desktop\text.txt", content);
        }
    }
    public class MyClass{
        public string content;
    }
    #endregion


Top