【问题标题】:Reflection: different ways to retrieve property value反射:获取属性值的不同方式
【发布时间】:2010-03-03 11:52:36
【问题描述】:

我正在通过以下代码检索 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)

【问题讨论】:

    标签: reflection c#-2.0


    【解决方案1】:

    其实没有区别。使用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);
    }
    

    这里的实际类型是 RuntimePropertyInfoPropertyInfo 是一个抽象类,不提供 GetValue 的实现)。

    【讨论】:

      猜你喜欢
      • 2011-10-02
      • 2013-01-16
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多