C# 反射

2023-10-21 17:28:27 浏览数 (2)

1. 获取程序集

代码语言:javascript复制
                    Assembly assembly = Assembly.Load("Ruanmou.DB.MySql");
                    //1 动态加载 一个完整dll名称不需要后缀  从exe所在的路径进行查找
                    Assembly assembly1 = Assembly.LoadFile(@"D:ruanmouonline1220181212Advanced12Course2ReflectionMyReflectionMyReflectionbinDebugRuanmou.DB.MySql.dll");//完整路径
                    Assembly assembly2 = Assembly.LoadFrom("Ruanmou.DB.MySql.dll");//当前路径
                    Assembly assembly3 = Assembly.LoadFrom(@"D:ruanmouonline1220181212Advanced12Course2ReflectionMyReflectionMyReflectionbinDebugRuanmou.DB.MySql.dll");//当前路径

2. 获取类型,创建对象,调用方法

代码语言:javascript复制
                    Console.WriteLine("************************Reflection************************");
                    Assembly assembly = Assembly.Load("Ruanmou.DB.MySql");//1 动态加载
                    Type type = assembly.GetType("Ruanmou.DB.MySql.MySqlHelper");//2 获取类型 完整类型名称
                    object oDBHelper = Activator.CreateInstance(type);//3 创建对象
             
                    IDBHelper iDBHelper = oDBHelper as IDBHelper;//4 类型转换  不报错,类型不对就返回null
                    iDBHelper.Query();//5 方法调用

3. 获取不同的构造函数, 根据不同的构造函数创建不同的实例对象

代码语言:javascript复制
                    Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.ReflectionTest");
                    foreach (ConstructorInfo ctor in type.GetConstructors())
                    {
                        Console.WriteLine(ctor.Name);
                        foreach (var parameter in ctor.GetParameters())
                        {
                            Console.WriteLine(parameter.ParameterType);
                        }
                    }
                    object oTest1 = Activator.CreateInstance(type);
                    object oTest2 = Activator.CreateInstance(type, new object[] { 123 });
                    object oTest3 = Activator.CreateInstance(type, new object[] { "陌殇" });

4. 反射,创建单例的实例对象

代码语言:javascript复制
                     //反射破坏单例---就是反射调用私有构造函数
                    Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.Singleton");
                    Singleton singletonA = (Singleton)Activator.CreateInstance(type, true);
                    Singleton singletonB = (Singleton)Activator.CreateInstance(type, true);
                    Singleton singletonC = (Singleton)Activator.CreateInstance(type, true);
                    Singleton singletonD = (Singleton)Activator.CreateInstance(type, true);
                    Console.WriteLine($"{object.ReferenceEquals(singletonA, singletonD)}");

5,  反射,创建泛型类实例对象

代码语言:javascript复制
                    Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.GenericClass`3");
                    //GenericClass<string, int, DateTime> genicClass = new GenericClass<string, int, DateTime>();
                    //object oGeneric = Activator.CreateInstance(type);
                    Type typeMake = type.MakeGenericType(new Type[] { typeof(string), typeof(int), typeof(DateTime) });
                    object oGeneric = Activator.CreateInstance(typeMake);

6.  反射,调用重载方法

代码语言:javascript复制
                   Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.ReflectionTest");
                    object oTest = Activator.CreateInstance(type);
                    foreach (var method in type.GetMethods())
                    {
                        Console.WriteLine(method.Name);
                        foreach (var parameter in method.GetParameters())
                        {
                            Console.WriteLine($"{parameter.Name}  {parameter.ParameterType}");
                        }
                    }
               
                    {
                        MethodInfo method = type.GetMethod("Show1");
                        //if()
                        method.Invoke(oTest, null);
                    }
                    {
                        MethodInfo method = type.GetMethod("Show2");
                        method.Invoke(oTest, new object[] { 123 });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { });
                        method.Invoke(oTest, null);
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(int) });
                        method.Invoke(oTest, new object[] { 123 });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(string) });
                        method.Invoke(oTest, new object[] { "一生为你" });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(int), typeof(string) });
                        method.Invoke(oTest, new object[] { 234, "心欲无痕" });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(string), typeof(int) });
                        method.Invoke(oTest, new object[] { "PHS", 345 });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show5");
                        method.Invoke(oTest, new object[] { "张中魁" });//静态方法实例可以要
                    }
                    {
                        MethodInfo method = type.GetMethod("Show5");
                        method.Invoke(null, new object[] { "张中魁" });//静态方法实例也可以不要
                    }

7. 反射,调用私有方法

代码语言:javascript复制
                    Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.ReflectionTest");
                    object oTest = Activator.CreateInstance(type);
                    var method = type.GetMethod("Show4", BindingFlags.Instance | BindingFlags.NonPublic);
                    method.Invoke(oTest, new object[] { "我是老王" });

8. 反射,调用泛型方法

代码语言:javascript复制
                    Console.WriteLine("********************GenericMethod********************");
                    Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.GenericMethod");
                    object oGeneric = Activator.CreateInstance(type);
                    //foreach (var item in type.GetMethods())
                    //{
                    //    Console.WriteLine(item.Name);
                    //}
                    MethodInfo method = type.GetMethod("Show");
                    var methodNew = method.MakeGenericMethod(new Type[] { typeof(int), typeof(string), typeof(DateTime) });
                    object oReturn = methodNew.Invoke(oGeneric, new object[] { 123, "董小姐", DateTime.Now });

9. 反射,调用泛型类的泛型方法

代码语言:javascript复制
                    Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.GenericDouble`1").MakeGenericType(typeof(int));
                    object oObject = Activator.CreateInstance(type);
                    MethodInfo method = type.GetMethod("Show").MakeGenericMethod(typeof(string), typeof(DateTime));
                    method.Invoke(oObject, new object[] { 345, "感谢有梦", DateTime.Now });

10. 反射,ORM

代码语言:javascript复制
                    Type type = typeof(People);
                    object oPeople = Activator.CreateInstance(type);
                    foreach (var prop in type.GetProperties())
                    {
                        Console.WriteLine($"{type.Name}.{prop.Name}={prop.GetValue(oPeople)}");
                        if (prop.Name.Equals("Id"))
                        {
                            prop.SetValue(oPeople, 234);
                        }
                        else if (prop.Name.Equals("Name"))
                        {
                            prop.SetValue(oPeople, "饿了么");
                        }
                        Console.WriteLine($"{type.Name}.{prop.Name}={prop.GetValue(oPeople)}");
                    }
                    foreach (var field in type.GetFields())
                    {
                        Console.WriteLine($"{type.Name}.{field.Name}={field.GetValue(oPeople)}");
                        if (field.Name.Equals("Description"))
                        {
                            field.SetValue(oPeople, "并不是外卖,也不是真的饿了");
                        }
                        Console.WriteLine($"{type.Name}.{field.Name}={field.GetValue(oPeople)}");
                    }

11,  反射,DTO

代码语言:javascript复制
                    Type typePeople = typeof(People);

                    Type typePeopleDTO = typeof(PeopleDTO);
                    object peopleDTO = Activator.CreateInstance(typePeopleDTO);
                    foreach (var prop in typePeopleDTO.GetProperties())
                    {
                        
                        //if (prop.Name.Equals("Id"))
                        //{
                        //    //object value = typePeople.GetProperty("Id").GetValue(people);
                        //    object value = typePeople.GetProperty(prop.Name).GetValue(people);
                        //    prop.SetValue(peopleDTO, value);
                        //}
                        //else if (prop.Name.Equals("Name"))
                        //{
                        //    //object value = typePeople.GetProperty("Name").GetValue(people);
                        //    object value = typePeople.GetProperty(prop.Name).GetValue(people);
                        //    prop.SetValue(peopleDTO, value);
                        //}
                        object value = typePeople.GetProperty(prop.Name).GetValue(people);
                        prop.SetValue(peopleDTO, value);
                    }
                    foreach (var filed in typePeopleDTO.GetFields())
                    {
                        object value = typePeople.GetField(filed.Name).GetValue(people);
                        filed.SetValue(peopleDTO, value);
                    }

知识介绍:https://blog.csdn.net/sinolover/article/details/104159239

0 人点赞