排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256
50010702506256
欢迎加群交流技术
分类:
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 调用标志表示要对成员采取的操作:
//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);评价