【问题标题】:Dynamically invoke the getter of property动态调用属性的getter
【发布时间】:2020-04-29 03:28:38
【问题描述】:

我正在尝试动态获取属性的 get 值,但是遇到了异常:

System.Reflection.TargetParameterCountException: '参数计数不匹配。'

object result = null;

....

MethodInfo getMethod;
if ((getMethod = p.GetGetMethod(true)) != null)
{
    var openGetterType = typeof(Func<,>);
    var concreteGetterType = openGetterType.MakeGenericType(typeResult, p.PropertyType);
    var getterInvocation = Delegate.CreateDelegate(concreteGetterType, null, getMethod);

    var value = getterInvocation.DynamicInvoke(); //exception thrown here
    if (value != null)
    {
        p.SetValue(result, value, null);
    }
}

备注:

  • 我试图避免使用p.GetValue(),因为它很慢。
  • 当我尝试调用 getter 时,我认为没有必要将任何值传递给 getterInvocation.DynamicInvoke()

【问题讨论】:

标签: c# .net


【解决方案1】:

我解决了这个问题。

我需要将源对象传递给 DynamicInvoke。

var value = getterInvocation.DynamicInvoke(source)

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 2012-10-05
    • 2011-01-28
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 2020-03-03
    • 2023-03-26
    • 2023-04-06
    相关资源
    最近更新 更多