首页 > 代码库 > .net Reflection(反射)- 二

.net Reflection(反射)- 二

反射 Reflection 中访问方法 

新建一个ClassLibrary类库:

    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" ;
        }   
    }

 

    /// <summary>
    /// 反射
    /// </summary>
    class Program
    {


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

            //无参数 返回
            object value = http://www.mamicode.com/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和 }

还可以通过 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]);
              }
          }