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#

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

作者:weihanli

出处:https://www.cnblogs.com/weihanli/p/11290416.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   WeihanLi  阅读(2572)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2015-08-02 windows上JSP开发环境全搭建
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu