【问题标题】:Retrieve "property getter" from the property name从属性名称中检索“属性获取器”
【发布时间】: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&lt;object&gt;,因为该属性的类型仅在运行时可用。

它可以完美运行,但当属性是引用类型时。当它是一个值类型时,比如 int,它会抛出一个 System.ArgumentException

无法绑定到目标方法,因为它的签名或安全性 透明度与委托类型的透明度不兼容。

【问题讨论】:

  • 将您的方法转换为泛型类型
  • 我不能用它来概括。它本质上是动态的!

标签: c# dynamic reflection


【解决方案1】:

您可以使用反射构造委托类型:

var delegateType = typeof(Func<>).MakeGenericType(propInfo.PropertyType);
var deleg = propInfo.GetMethod.CreateDelegate(delegateType, instance);

当然你不能静态地转换它,因为你在编译时不知道它,你需要使方法返回动态类型并返回委托而不进行转换。

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 2021-12-04
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    相关资源
    最近更新 更多