Loading

C# 通过反射调用 Func 委托

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

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

posted @ 2019-08-02 18:08  WeihanLi  阅读(2519)  评论(0编辑  收藏  举报