gpt4 book ai didi

c# - 从属性名称中检索 "property getter"

转载 作者:太空宇宙 更新时间:2023-11-03 10:36:12 25 4
gpt4 key购买 nike

我一直在使用此方法根据属性名称检索属性 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

Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

最佳答案

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

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

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

关于c# - 从属性名称中检索 "property getter",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27719576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com