1. 程式人生 > >反射簡單調用

反射簡單調用

console 實例 ons stat 參數 容易 方法 write method

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             string path = @"J:\beforesoft\Test\NET.Reflection\bin\Debug\NET.Reflection.dll";
 6             Assembly ass = Assembly.LoadFile(path);
 7             //獲取類
 8             //第一種方法,在類的構造函數是無參時使用方便,在有參時就不容易實現
9 //object obj = ass.CreateInstance("NET.Reflection.Person"); 10 //Type type = obj.GetType(); 11 //第二種方法,通過獲得類型的構造函數來實例化對象,在構造函數是有參時也容易實現 12 Type type = ass.GetType("NET.Reflection.Person"); 13 //ConstructorInfo construct = type .GetConstructor(new Type[0]);
14 //object obj = construct.Invoke(null); 15 ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(string), typeof(int) });//構造函數調用有參構造函數 16 object obj = constructor.Invoke(new object[] { "張三", 20 }); 17 MethodInfo method1 = type.GetMethod("
SayName");//得到無參公有方法 18 MethodInfo method2 = type.GetMethod("SayAge", BindingFlags.Instance | BindingFlags.NonPublic);//得到私有方法 19 MethodInfo method3 = type.GetMethod("GetName", new Type[] { typeof(string) });//得到帶參數的公有方法(後面的Type類型可以省略,但如果是重載方法就不能省) 20 MethodInfo method4 = type.GetMethod("GetName", new Type[0]); 21 MethodInfo method5 = type.GetMethod("PrintAge");//得到參數是ref的的方法 22 PropertyInfo Name = type.GetProperty("Name");//得到屬性 23 PropertyInfo Age = type.GetProperty("Age"); 24 FieldInfo name = type.GetField("name", BindingFlags.Instance | BindingFlags.NonPublic);//得到字段(全是私有的) 25 Name.SetValue(obj, "李四", null);//給Name設值,後面的null是對應的索引器 26 Age.SetValue(obj, 23, null); 27 method1.Invoke(obj, null); 28 29 method2.Invoke(obj, null); 30 31 Console.WriteLine(method3.Invoke(obj, new object[] { "王五" }));//調用有返回值的方法 32 33 method4.Invoke(obj, null); 34 35 method5.Invoke(obj, new object[] { 14 });//調用參數是ref的方法 36 Console.ReadLine(); 37 } 38 }

反射簡單調用