• [小技巧]C# 反射


    定义

    反射提供描述程序集、模块和类型的对象(Type 类型)。 可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型,然后调用其方法或访问器字段和属性。 如果代码中使用了特性,可以利用反射来访问它们。

    Namespace

    using System;
    using System.Reflection; 
    
    • 1
    • 2

    场景

    反射一般用于动态工厂,主要用于根据配置的数据信息反射出操作对象,动态加载对象进行逻辑处理等。

    示例

    简单反射一个对象进行操作

    • 显示效果
      在这里插入图片描述
    • 代码
      private void button6_Click(object sender, EventArgs e)
            {
                var 一个配置类型名称 = "一些可行性想法的验证测试.TT";
                var type = Assembly.GetExecutingAssembly().GetType(一个配置类型名称);
                var t = Activator.CreateInstance(type);
                MessageBox.Show(t.GetType().FullName);
            }
    
    //单独写一个类
     public class TT
        {
            public string Name { get; set; } = "TEST";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    反射一个有参构造函数的对象

    主要就是上述方式,在最后一个方法中需要添加object[] 类型的参数

    object[] para=new object[]{1,2,3}
    Activator.CreateInstance(type,para)
    
    • 1
    • 2

    反射一个泛型类型的对象

    • 反射代码块
       var types = Assembly.GetAssembly(this.GetType()).GetTypes();
                var type = types.FirstOrDefault(t => t.Name == "People`1");
                var paraTypes = types.Where(t => t.Name == "TT").ToArray();
                type = type.MakeGenericType(paraTypes);
                var s = Activator.CreateInstance(type);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • People类
      public class People<T> where T : TT, new()
        {
            public People(string id)
            {
    
            }
            public T Get(int id)
            {
                var t = new T();
                return t;
            }
    
            public static string GETRT<TR, TX>(Type trtype, TX tx)
            {
                return tx.ToString();
            }
            public static string GETRT<TR, TX>(Type trtype)
            {
                return "11";
            }
    
            public static TX GETRT<TR, TX>(TR trtype, TX i, params object[] others)
            {
                return default(TX);
            }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    简单反射一个方法进行操作

    • 显示效果
      -在这里插入图片描述
    • 代码
    public class TT
        {
            public string Name { get; set; } = "TEST";
    
            public void Msg(string name)
            {
                MessageBox.Show("Hello " + name);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 反射部分代码
     private void button7_Click(object sender, EventArgs e)
            {
    
                var 一个配置类型名称 = "一些可行性想法的验证测试.TT";
                var type = Assembly.GetExecutingAssembly().GetType(一个配置类型名称);
                var t = Activator.CreateInstance(type);
                var method = t.GetType().GetMethod("Msg");
                method.Invoke(t, new object[] { "张三" });
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    反射一个泛型方法进行操作

    • 反射部分代码块
    #region 反射泛型对象
                var types = Assembly.GetAssembly(this.GetType()).GetTypes();
                var type = types.FirstOrDefault(t => t.Name == "People`1");
                var paraTypes = types.Where(t => t.Name == "TT").ToArray();
                type = type.MakeGenericType(paraTypes);
                var s = Activator.CreateInstance(type);
    #endregion     
    
    #region 反射泛型方法
                var method = s.GetType().GetMethod("GETRT", new Type[] { typeof(Type) });
                method = method.MakeGenericMethod(new Type[] { typeof(string), typeof(object) });
                var r = method.Invoke(null, new object[] { typeof(string), 0 });
                MessageBox.Show(r.ToString());
    #endregion
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    上述代码中用到的Penple类见上面。

    反射一个静态(Static)方法

    接上面代码,静态方法 就是在invoke时不需要指定第一个参数

      var r = method.Invoke(null, new object[] { typeof(string), 0 });
    
    • 1
  • 相关阅读:
    手把手教学一文安装Keil5(MDK)固件支持包
    Azure Function 时区设置
    【乳腺癌诊断】基于聚类和遗传模糊算法乳腺癌(诊断)分析(Matlab代码实现)
    【C语言】初阶测试 (带讲解)
    可选的优化器:Adam、SGD、Adagrad、RMSprop、Sparse Adam
    从零学习开发一个RISC-V操作系统(一)丨计算机组成原理相关知识与RISC-V指令集简介
    MySQL - mvcc
    安装mmcv及GPU版本的pytorch及torchvision
    SpringBoot中Bean的条件装配
    【每日一读】Graph Recurrent Networks With Attributed Random Walks
  • 原文地址:https://blog.csdn.net/iml6yu/article/details/127905447