简体   繁体   中英

Dynamically invoke the getter of property

I'm trying to get dynamically the get value of a property, however, I got an exception:

System.Reflection.TargetParameterCountException: 'Parameter count mismatch.'

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

Remarks:

  • I'm trying to avoid using the p.GetValue() because is slow.
  • As I'm trying to invoke a getter I thought that it's not necessary to pass any value to getterInvocation.DynamicInvoke()

I solve the problem.

I need to pass the source object to the DynamicInvoke.

var value = getterInvocation.DynamicInvoke(source)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM