反射入门基础

4068人阅读 2021/3/31 19:59 总访问:652468 评论:3 收藏:0 手机
分类: Csharp

反射可以根据字符串创建对象(类全名,类库名)
反射可以访问属性,而且可以访问私有属性,并且给属性赋值
反射可以访问字段,而且可以访问私有字段,并且给字段赋值
反射可以调用方法,而且可以调用私有方法

存在一个类

   public class TableInfo
    {
        public int Sid { get; set; }
        public string UserName { get; set; }
        public int? Sum { get; set; }
        public int? Max { get; set; }
        public int? Min { get; set; }
        public double Avg { get; set; }
        public string Father { get; set; }
        public string Mather { get; set; }
     }

通过反射拿到属性(typeof或者GetType)

           //反射根据字段拿到属性
            var type = typeof(TableInfo).GetProperty("Sum");
            
            TableInfo tableinfo = new TableInfo();
            var type = tableinfo.GetType().GetProperty("Sum");

通过反射调用方法

           //TableInfo中存在AA方法
            public void AA()
        {
            Console.WriteLine("aa");
        }

getMethod第一个参数是方法名,第二个参数是该方法的参数类型
因为存在同方法名不同参数这种情况,所以只有同时指定方法名和参数类型才能唯一确定一个方法
Invoke第一个参数是对象名,第二个的方法的参数 如果有参数则需要传递一个object集合     new object[] {"Hello"}

//实例化对象
TableInfo tableinfo = new TableInfo();

typeof(TableInfo).GetMethod("AA").Invoke(tableinfo, null);

反射调用私有方法

可以使用下列 BindingFlags 调用标志表示要对成员采取的操作:

CreateInstance,表示调用构造函数。忽略 name。对其他调用标志无效。
InvokeMethod,表示调用方法,而不调用构造函数或类型初始值设定项。对 SetField 或 SetProperty 无效。
GetField,表示获取字段值。对 SetField 无效。
SetField,表示设置字段值。对 GetField 无效。
GetProperty,表示获取属性。对 SetProperty 无效。
SetProperty 表示设置属性。对 GetProperty 无效。
BindingFlags.Instance                     : 对象实例
BindingFlags.Static                          : 静态成员 
BindingFlags.Public                         : 指可在搜索中包含公共成员
BindingFlags.NonPublic                 : 指可在搜索中包含非公共成员(即私有成员和受保护的成员)
BindingFlags.FlattenHierarchy      : 指可包含层次结构上的静态成员
BindingFlags.IgnoreCase               : 表示忽略 name 的大小写
BindingFlags.DeclaredOnly           : 仅搜索 Type 上声明的成员,而不搜索被简单继承的成员
BindingFlags.CreateInstance        : 表示调用构造函数。忽略 name。对其他调用标志无效

//TableInfo中存在DD方法
private void DD()
        {
            Console.WriteLine("私有方法被调用");
        }

调用

//实例化对象
TableInfo tableinfo = new TableInfo();
//私有方法BindingFlags.NonPublic|BindingFlags.Instance 
typeof(TableInfo).GetMethod("DD",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance).Invoke(tableinfo, null);

反射调用泛型方法

 //TableInfo中存在BB方法
 public void BB<T>()
        {
            Console.WriteLine("泛型方法被调用");
        }

调用

//实例化对象
TableInfo tableinfo = new TableInfo();

//通过字段拿到属性
var type = typeof(TableInfo).GetProperty("Sum");

//通过属性传递方法名
var FunB =  typeof(TableInfo).GetMethod("BB");
//指定泛型类型(有返回值)
FunB = FunB.MakeGenericMethod(type.PropertyType);
//调用方法
FunB.Invoke(tableinfo, null);


评价
脚踏实地,一步一个脚印
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术