using System; using System.Reflection; // 反射 (Reflection) // 可以通过类,属性,方法的名字来使用类,属性,方法 namespace A { class Person { public int age; private int score; private readonly int money = 1000; private static int ac; public Person() { Console.WriteLine("Person的构造方法被调用"); } public Person(int a, int b) { Console.WriteLine("Person的有参构造被调用"); } public override string ToString() { return "age = " + age + "; score = " + score + "; money = " + money; } public void Show(int a) { Console.WriteLine("Show -> " + a); } private static int Display(int a) { return a * a; } private void Add(int a) { Console.WriteLine("Add(int)"); } private void Add(int a, string b) { Console.WriteLine("Add(int, string)"); } } class Test { public static void Main(string[] args) { // 实例化一个Person对象 // 1、获取这个类的类型 Type t = Type.GetType("A.Person"); Console.WriteLine(t); // 2、通过反射实例化一个类的对象 // 通过无参的构造方法来实例化对象 object obj = Activator.CreateInstance(t); // 通过有参的构造方法来实例化对象 object obj1 = Activator.CreateInstance(t, new object[] { 1, 2 }); // 3、通过属性名来访问属性(public, instance) FieldInfo f = t.GetField("age"); // xiaoming.age = 10; f.SetValue(obj, 20); Console.WriteLine(obj); Console.WriteLine(f.GetValue(obj)); // 4、访问属性,非公开的 // BindingFlags默认值: BindingFlags.Public | BindingFlags.Instance FieldInfo ff = t.GetField("score", BindingFlags.NonPublic | BindingFlags.Instance); ff.SetValue(obj, 100); Console.WriteLine(obj); // 5、访问属性,readonly FieldInfo fff = t.GetField("money", BindingFlags.NonPublic | BindingFlags.Instance); fff.SetValue(obj, 9999); Console.WriteLine(obj); // 6、访问属性,静态的 FieldInfo ac = t.GetField("ac", BindingFlags.NonPublic | BindingFlags.Static); ac.SetValue(null, 10000); Console.WriteLine(ac.GetValue(null)); // 7、访问方法(public 没有重载的方法) MethodInfo m0 = t.GetMethod("Show"); m0.Invoke(obj, new object[] { 1 }); // 8、访问方法(Nonpublic, static) MethodInfo m1 = t.GetMethod("Display", BindingFlags.NonPublic | BindingFlags.Static); object result = m1.Invoke(null, new object[] { 10 }); Console.WriteLine(result); // 9、访问有重载的方法 MethodInfo m2 = t.GetMethod("Add", BindingFlags.NonPublic|BindingFlags.Instance, null, new Type[] { typeof(int), typeof(string) }, null); m2.Invoke(obj, new object[] { 1, "hello" }); } } }