C# 调用程序集方法

  • 加载程序集 (Assembly类)

使用 Assembly 类可以加载程序集、浏览程序集的元数据和构成部分、发现程序集中包含的类型以及创建这些类型的实例

    // 加载该路径的程序集
    Assembly ass = Assembly.LoadFrom(@"C:Users肖黎望Desktop
et练习ConsoleApplication1AnimalinDebugAnimal.dll");
  • 获得该程序集内所有文件的 Type (Type类),通过Type对象可以获得类的信息(类名、命名空间、方法、属性....)

反射的核心类-Type,封装了关于类型的元数据,是进行反射的入口。当获得了类型的Type对象后,可以根据Type提供的书信和方法获得这个类型的一切信息,包括字段,属性,事件,参数,构造函数等

            //GetTypes 获得该程序集下所有类的Type
            Type[] tps = ass.GetTypes();
            //获得所有公共类型
            Type[] tps = ass.GetExportedTypes();
            //通过指定类名获取该类的 Type

            foreach (Type tp in tps)
            {
                //命名空间.类名
                Console.WriteLine(tp.FullName);
                //类名
                Console.WriteLine(tp.Name);
                //所有方法的信息 数组
                MethodInfo[] meths = tp.GetMethods();
                //MethodInfo 保存方法的所有信息
                foreach (MethodInfo meth in meths)
                {
                    //获得方法名
                    Console.WriteLine(meth.Name);
                }
            }

我们来看一下Type给我们提供的一些方法:

            Type cat_type = ass.GetType("Animal.Cat");
            Type animal_type = ass.GetType("Animal.Animal");

            //IsAssignableFrom 判断 animal_type 是不是 cat_type 的父类
            animal_type.IsAssignableFrom(cat_type); //返回 TRUE

            //IsSubclassOf 判断是不是 animal_type 的子类
            cat_type.IsSubclassOf(animal_type); //返回TRUE

            Object obj = Activator.CreateInstance(cat_type);
            //IsInstanceOfType  判断obj是不是cat_type 的对象
            cat_type.IsInstanceOfType(obj); //返回TRUE
            //判断obj是不是animal_type 的对象
            animal_type.IsInstanceOfType(obj); //返回TRUE
  • 创建对象(Activator类)
        object obj = Activator.CreateInstance(cat_type);
  • 调用方法
            Type cat_type = ass.GetType("Animal.Cat");
            
            //创建对象
            object obj = Activator.CreateInstance(cat_type);
            //获取属性
            PropertyInfo prop = cat_type.GetProperty("Food");
            //设置属性
            prop.SetValue(obj, "");
            //获取方法
            MethodInfo meth = cat_type.GetMethod("eat");
            //设置参数,如果没有设置 null,调用方法
            meth.Invoke(obj,null);
原文地址:https://www.cnblogs.com/xiaoliwang/p/9516508.html