I've been using this method to retrieve a property getter based on the name of the property.
public static Func<object> GetGetterFromProperty(object instance, string propertyName)
{
var propInfo = instance.GetType().GetTypeInfo().GetDeclaredProperty(propertyName);
var deleg = propInfo.GetMethod.CreateDelegate(typeof(Func<object>), instance);
var action = (Func<object>)deleg;
return action;
}
It returns a Func<object>
since the type of the property is available only at runtime.
It works perfectly, but ONLY when the property is a reference type. When it's a value type, like int, it throws a System.ArgumentException
Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
Aucun commentaire:
Enregistrer un commentaire