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

分享一下,希望對你有幫助~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM