2010-03-03 69 views
5

我通過下面的代碼檢索性能的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) 

回答

4

事實上, 沒有區別。你可以看到的GetValue使用Reflector實現:

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提供實現)。