【发布时间】:2014-12-31 18:59:22
【问题描述】:
我一直在使用这种方法来根据属性名称检索属性 getter。
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;
}
它返回一个Func<object>,因为该属性的类型仅在运行时可用。
它可以完美运行,但仅当属性是引用类型时。当它是一个值类型时,比如 int,它会抛出一个 System.ArgumentException
无法绑定到目标方法,因为它的签名或安全性 透明度与委托类型的透明度不兼容。
【问题讨论】:
-
将您的方法转换为泛型类型
-
我不能用它来概括。它本质上是动态的!
标签: c# dynamic reflection