gpt4 book ai didi

反射(reflection):检索属性值的不同方式

转载 作者:行者123 更新时间:2023-12-04 20:24:49 26 4
gpt4 key购买 nike

我正在通过以下代码检索 IEnumerable 属性列表:

BindingFlags bindingFlag = BindingFlags.Instance | BindingFlags.Public;  
var dataProperties = typeof(myParentObject).GetProperties(bindingFlag);

然后我遍历列表并检索每个属性的值。

我遇到过两种不同的方法来做到这一点,只是想知道它们之间有什么区别:

1)
object propertyValue = property.GetGetMethod().Invoke(myObject, null);

2)
object propertValue = property.GetValue(myObject, null)

最佳答案

事实上,没有区别。您可以使用 Reflector 查看 GetValue 的实现:

public override object GetValue(object obj, BindingFlags invokeAttr,
Binder binder, object[] index,
CultureInfo culture)
{
MethodInfo getMethod = this.GetGetMethod(true);
if (getMethod == null)
{
throw new ArgumentException(
Environment.GetResourceString("Arg_GetMethNotFnd"));
}
return getMethod.Invoke(obj, invokeAttr, binder, index, null);
}

这里的实际类型是 RuntimePropertyInfo( PropertyInfo 是一个不提供 GetValue 实现的抽象类)。

关于反射(reflection):检索属性值的不同方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2370893/

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