.net Reflection(反射)- 二

时间:2014-05-09 00:19:30   收藏:0   阅读:367

反射 Reflection 中访问方法 

新建一个ClassLibrary类库:

bubuko.com,布布扣
    public class Student
    {
        public string Name
        { get; set; }
        public string School
        { get; set; }

        public int Sum(int a, int b)
        {
            return a + b;
        }
        public string GetName()
        {
            return "this is book" ;
        }   
    }
bubuko.com,布布扣

 

bubuko.com,布布扣
    /// <summary>
    /// 反射
    /// </summary>
    class Program
    {


        static void Main(string[] args)
        {
            
            Assembly assembly = Assembly.Load("ClassLibrary");
//调用 程序集 类的方法
            //创建该对象的实例,object类型,参数(名称空间+类)   
            object instances = assembly.CreateInstance("ClassLibrary.Student");

            //无参数 返回
            object value = type.GetMethod("GetName").Invoke(instances, null);
       //返回this is book
            //有参
            object[] params_obj = new object[2];
            params_obj[0] = 12; 
            params_obj[1] = 23;
            object value1 = type.GetMethod("Sum").Invoke(instances, params_obj);
   //返回a b和 }
bubuko.com,布布扣

还可以通过 FindInterfaces 方法返回 接口信息 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//获取程序集接口 Stu 继承的所有接口
          Type t = typeof(Stu);
          Type[] interfaces = t.FindInterfaces(TypeFilter, assembly);
 
          //显示每个接口信息
          foreach (Type i in interfaces)
          {
              //获取映射接口方法的类型的方法
              InterfaceMapping mapping = t.GetInterfaceMap(i);
 
              for (int j = 0; j < mapping.InterfaceMethods.Length; j++)
              {
                  Console.WriteLine(" {0} 实现的 {1}", mapping.InterfaceMethods[j], mapping.TargetMethods[j]);
              }
          }
           

  

 

 

.net Reflection(反射)- 二,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!