C # reflection by calling Func delegate

Original: C # reflection by calling Func delegate

C # reflection by calling Func delegate

Intro

Recently my NPOI extension library has increased, the ability to customize the output, you can customize the content to set a Func delegate to export, details please see https://www.cnblogs.com/weihanli/p/custom-column- -Support-for-the Output weihanli-npoi.html , you can easily set up by Func, but the time to call a little trouble

Reflection call

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 });
    }
}

Gets delegate method: GetProperty("Method")
get target to be executed when the method:GetProperty("Target")

The method is a delegate MethodInfoobject that can be converted to MethodInfoan object, then call its Invokemethod, passing parameters and other information

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

Memo

I hope, for your help ~

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11300679.html