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