您的位置:首页 > 编程语言 > C#

C# 通过反射调用 Func 委托

2019-08-02 18:08 951 查看

C# 通过反射调用 Func 委托

Intro

最近我的 NPOI 扩展库增加了,自定义输出的功能,可以自定义一个 Func 委托来设置要导出的内容,详细介绍请查看 https://www.cnblogs.com/weihanli/p/custom-column-output-support-for-weihanli-npoi.html,通过 Func 可以很方便设置,但是要调用的时候就有点麻烦了

反射调用

var propertyValue = property.GetValueGetter<TEntity>().Invoke(entity);
var propertyType = typeof(PropertySetting<,>).MakeGenericType(_entityType, p.PropertyType);
var formatterFunc = propertyType.GetProperty("ColumnFormatterFunc")?.GetValueGetter().Invoke(setting);

if (null != formatterFunc)
{
var funcType = typeof(Func<,,>).MakeGenericType(_entityType, key.PropertyType, typeof(object));

var method = funcType.GetProperty("Method")?.GetValueGetter().Invoke(formatterFunc) as MethodInfo;
var target = funcType.GetProperty("Target")?.GetValueGetter().Invoke(formatterFunc);

if (null != method && target != null)
{
// apply custom formatterFunc
// 这里调用方法的时候要注意,method的 invoke 对象是 target
propertyValue = method.Invoke(target, new[] { entityList[i], propertyValue });
}
}

获取委托的方法:

GetProperty("Method")

获取要执行方法时的target:
GetProperty("Target")

委托的方法是一个

MethodInfo
对象,可以转为
MethodInfo
对象,然后调用其
Invoke
方法,并传递参数等信息

method.Invoke(target, new object[]{ parameters });

Memo

分享一下,希望对你有帮助~

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: