C#反射基本使用

2-最新2021C#.NET5--语法之反射_哔哩哔哩_bilibili

一、什么是反射和dll文件加载

1、反射是操作dll文件的一个类库

  • 反射需要引用包:using System.Reflection;
    2、dll文件什么?在项目文件的\bin\Debug\net6.0目录下


二、反射的基本使用

1、加载DLL文件

  • 找到dll文件

  • 通过Reflection反射类库中的方法来操作dll文件

  • 方案一代码 Load:从ReflectionTest项目中,读取Test项目的dll文件,在ReflectionTest项目中对Test项目添加引用



  • 方案二代码 LoadFile


  • 方案三代码 LoadFrom


二、通过反射调用构造方法

1、在Test项目中创建一个测试类Person

namespace Test
{
    public class Person
    {
        public Person()
        {
            Console.WriteLine("这里是Test项目中,Person类的,无参构造函数");
        }
        public Person(string value1)
        {
            Console.WriteLine($"这里是Test项目中,Person类的,有参构造函数,参数是:{value1}");
        }
        public Person(string value1,string value2)
        {
            Console.WriteLine($"这里是Test项目中,Person类的,有参构造函数,参数是:{value1} 和 {value2}");
        }
        public int Id { get; set; }
        public string Name { get; set; }

    }
}

2、在ReflectionTest项目中,通过反射,实例化Test项目中的Person类

using System.Reflection;

namespace ReflectionTest
{
    public class Program
    {
        public static void Main()
        {
            // --1、加载DLL文件
            Assembly assembly = Assembly.LoadFrom(
                @"C:\\Users\\Raoli\\Desktop\\T" +
                @"est\\Test\\Test\\bin\\Debug\\net6.0\\Test.dll");
            // --2、获取DLL文件中的某个具体类型,即Test项目中的Person类型
            Type type = assembly.GetType("Test.Person");
            // --3、实例化
            object objTest1 = Activator.CreateInstance(type); // 动态实例化,调用Person的 无 参构造函数
            object objTest2 = Activator.CreateInstance(type, new object[] { "测试1" }); // 动态实例化,调用Person的 1个参数的,有 参构造函数
            object objTest3 = Activator.CreateInstance(type, new object[] { "测试1","测试2" }); // 动态实例化,调用Person的 2个参数的,有 参构造函数
        }
    }
}

三、调用私有构造方法

1、Test项目(被调用的dll文件)代码

namespace Test
{
    public class Person
    {

        private Person()
        {
            Console.WriteLine("这里是Test项目中,Person类的,私有 无参构造函数");
        }
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

2、通过反射调用Person的私有构造函数

  • 关键就是true这个参数


    d

四、获取调用的dll文件中所有的类:GetTypes()

1、dll文件中有Student和Person类

using System.Reflection;

namespace ReflectionTest
{
    public class Program
    {
        public static void Main()
        {
            // --1、加载DLL文件
            Assembly assembly = Assembly.LoadFrom(
                @"C:\\Users\\Raoli\\Desktop\\T" +
                @"est\\Test\\Test\\bin\\Debug\\net6.0\\Test.dll");
            // --2、获取dll文件中的所有类
            foreach (var item in assembly.GetTypes())
            {
                Console.WriteLine(item);
            }

        }
    }
}

五、获取某个具体类的所有构造参数信息

using System.Reflection;

namespace ReflectionTest
{
    public class Program
    {
        public static void Main()
        {
            // --1、加载DLL文件
            Assembly assembly = Assembly.LoadFrom(
                @"C:\\Users\\Raoli\\Desktop\\T" +
                @"est\\Test\\Test\\bin\\Debug\\net6.0\\Test.dll");
            // --2、获取DLL文件中的某个具体类型,即Test项目中的Person类型
            Type type = assembly.GetType("Test.Person");
            // --3、获取Person类的所有构造方法
            foreach (var ctor in type.GetConstructors())
            {
                Console.WriteLine($"构造方法:{ctor.Name}");
                // -4、获取构造方法的所有参数
                foreach (var param in ctor.GetParameters())
                {
                    Console.WriteLine($"构造方法的参数:{param.Name},参数类型{param.ParameterType}");
                }
            }
        }
    }
}

六、调用泛型方法和普通方法

1、Test项目中Person类的代码

namespace Test
{
    public class Person
    {
        // 非泛型无参方法
        public void Show1()
        {
            Console.WriteLine("非泛型无参方法");
        }
        // 非泛型有参方法
        public void Show2(int id ,string name)
        {
            Console.WriteLine($"非泛型有参方法,id:{id},name:{name}");
        }
        // 无参泛型方法
        public void Show3<T>()
        {
            Console.WriteLine("无参泛型方法");
        }
        // 有参泛型方法
        public void Show4<T>(int id,string name)
        {
            Console.WriteLine($"有参泛型方法,id:{id},name:{name}");
        }
    }
}

2、调用Person类的泛型方法和普通方法

using System.Reflection;

namespace ReflectionTest
{
    public class Program
    {
        public static void Main()
        {
            // --1、加载DLL文件
            Assembly assembly = Assembly.LoadFrom(
                @"C:\\Users\\Raoli\\Desktop\\T" +
                @"est\\Test\\Test\\bin\\Debug\\net6.0\\Test.dll");
            // --2、获取DLL文件中的某个具体类型,即Test项目中的Person类型
            Type type = assembly.GetType("Test.Person");
            // --3、创建实例
            object obj = Activator.CreateInstance(type,true);
            // --4、调用 无参泛型方法
            var method = type.GetMethod("Show3"); // 查找指定方法
            var genericMethod = method.MakeGenericMethod(new Type[] {typeof(int)}); // 指定泛型参数类型T
            genericMethod.Invoke(obj, new object[] { });
            // --5、调用 有参泛型方法
            var method1 = type.GetMethod("Show4"); // 查找指定方法
            var genericMethod1 = method1.MakeGenericMethod(new Type[] { typeof(int) }); // 指定泛型参数类型T
            genericMethod1.Invoke(obj, new object[] {1,"test"});
            // --6、调用 无参非泛型方法
            var method2 = type.GetMethod("Show1"); // 查找指定方法
            method2.Invoke(obj, new object[] {});
            // --6、调用 有参非泛型方法
            var method3 = type.GetMethod("Show2"); // 查找指定方法
            method3.Invoke(obj, new object[] { 2, "ttt" });
        }
    }
}

七、创建泛型类+调用泛型方法

1、查看泛型方法实际上对应的方法可知:类名命名考虑到了有几个泛型参数,如下图中有两个泛型参数,类的命名后面就带有2,那么通过反射调用的时候就要完整的写上类名,即加上2

2、泛型调用

using System.Reflection;

namespace ReflectionTest
{
    public class Program
    {
        public static void Main()
        {
            // --1、加载DLL文件
            Assembly assembly = Assembly.LoadFrom(
                @"C:\\Users\\Raoli\\Desktop\\T" +
                @"est\\Test\\Test\\bin\\Debug\\net6.0\\Test.dll");

            // --2、获取指定类型
            Type type = assembly.GetType("Test.GenericClass`2").MakeGenericType(typeof(int), typeof(string));

            // --3、实例化
            object obj = Activator.CreateInstance(type);

            // --4、调用泛型方法
            var method = type.GetMethod("GenericMethod").MakeGenericMethod(typeof(int));
            method.Invoke(obj, new object[] { });
        }
    }
}

八、设置属性的值和获取属性的值

using System.Reflection;

namespace ReflectionTest
{
    public class Program
    {
        public static void Main()
        {
            // --1、加载DLL文件
            Assembly assembly = Assembly.LoadFrom(
                @"C:\\Users\\Raoli\\Desktop\\T" +
                @"est\\Test\\Test\\bin\\Debug\\net6.0\\Test.dll");

            // --2、获取指定类型
            Type type = assembly.GetType("Test.Student");

            // --3、实例化
            object obj = Activator.CreateInstance(type);

            // --4、获取所有属性,并给 某个实例化对象 属性设置值
            foreach (var prop in type.GetProperties())
            {
                if (prop.Name.Equals("Name"))
                {
                    prop.SetValue(obj, "张三");
                }
                if (prop.Name.Equals("Id"))
                {
                    prop.SetValue(obj, 1);
                }
            }
            // --5、获取 某个实例化对象的 属性值
            foreach (var prop in type.GetProperties())
            {
                Console.WriteLine(prop.GetValue(obj));
            }
        }
    }
}

九、调用私有方法

using System.Reflection;

namespace ReflectionTest
{
    public class Program
    {
        public static void Main()
        {
            // --1、加载DLL文件
            Assembly assembly = Assembly.LoadFrom(
                @"C:\\Users\\Raoli\\Desktop\\T" +
                @"est\\Test\\Test\\bin\\Debug\\net6.0\\Test.dll");

            // --2、获取指定类型
            Type type = assembly.GetType("Test.Student");

            // --3、实例化
            object obj = Activator.CreateInstance(type);

            // --4、调用私有方法
            var method = type.GetMethod("PrivateMethod",BindingFlags.Instance | BindingFlags.NonPublic); // 找到私有方法
            method.Invoke(obj,null);
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,576评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,515评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,017评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,626评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,625评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,255评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,825评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,729评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,271评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,363评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,498评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,183评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,867评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,338评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,458评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,906评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,507评论 2 359

推荐阅读更多精彩内容