c#反射的使用和理解

在这里插入图片描述
先了解一下程序集的概念https://www.cnblogs.com/kevinWu7/p/10163545.html
在这里插入图片描述

namespace 反射小demo
{
    class Program
    {
        static void Main(string[] args)
        {
            //利用对象获取
            //首先加载程序集文件
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"ClassLibrary1.dll");
            Assembly ass = Assembly.LoadFile(path);
            //获取所有的公共type
            Type[] types =ass.GetExportedTypes();//gettypes不公开的数据也会获得
            foreach(Type item in types)
            {
                Console.WriteLine(item.Name);
                Console.WriteLine(item.FullName);
                Console.WriteLine(item.Namespace);
            }

            //或者可以直接Type t=typeof(Person)

            //调用引用文件中的类
            object o = ass.CreateInstance("ClassLibrary1.Student");
            Console.WriteLine(o.GetType());
            //另一种方式,给创建的对象添加参数
            Type t = ass.GetType("ClassLibrary1.Student");
            object o1 = Activator.CreateInstance(t,null);

            //获取数据源的属性数组
            PropertyInfo[] pros = o.GetType().GetProperties();
            //获取数据源的方法数组
            MethodInfo[] md = o.GetType().GetMethods();
            //调用某一个方法
            MethodInfo mdi = o.GetType().GetMethod("hello");
            mdi.Invoke(o, null);//执行获取的方法
            Console.ReadKey();

        }
        //使用反射是代码的可扩展性变得更强,可以在form中动态创建元素,引用dll文件
    }
}

这里的反射的用处可以跨程序集进行类方法等数据的使用读取

将简单工厂与反射结合写的计算器扩展性更强

namespace ProFactory
{
    public class Factory
    {
        public static operation GetOper(string type, int n1, int n2)
        {
            operation oper = null;
            //动态获得程序集
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plug");
            //然后获得files下的多有程序集文件
            string[] files = Directory.GetFiles(path, "*.dll");
            foreach (string item in files)
            {
                Assembly ass = Assembly.LoadFile(item);
                //获得程序集文件中公开的数据类型
                Type[] types = ass.GetExportedTypes();
                foreach (Type tt in types)
                {
                    //判断当前的数据类型是不是我需要的类型
                    if (tt.IsSubclassOf(typeof(operation)) && !tt.IsAbstract)
                    {
                        //创建子类对象,赋值给oper
                        oper = (operation)Activator.CreateInstance(tt, n1, n2);
                    }
                }
                if (type == oper.Type)
                {
                    break;
                }
                else
                {
                    oper = null;
                }
                
            }
            return oper;
        }
    }
}

可以不透漏源码文件将.exe文件和.dll文件放在一起就可以实现功能,当然记得一定要写扩展的说明文档

发布了43 篇原创文章 · 获赞 8 · 访问量 3927

猜你喜欢

转载自blog.csdn.net/MaYang_/article/details/100855096