码迷,mamicode.com
首页 > 其他好文 > 详细

反射简单调用

时间:2017-08-29 10:10:57      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:load   name   static   value   重载方法   sem   string   type   info   

 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     }

 

反射简单调用

标签:load   name   static   value   重载方法   sem   string   type   info   

原文地址:http://www.cnblogs.com/zkh0313/p/7446864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!