zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    MongoDB一键安装
    Mongo基本操作
    MongoDB AUTH结果验证及开启方法
    MongoDB AUTH结果验证
    MongoDB使用
    MongoDB-安装配置
    11204RAC-dbca建库脚本
    MySQL主从同步最佳实践
    实时抓取主从的同步状态
    守护神 Supervisor
  • 原文地址:https://www.cnblogs.com/weihanli/p/11290416.html
Copyright © 2011-2022 走看看