I'm retrieving an IEnumerable list of properties via following code:
BindingFlags bindingFlag = BindingFlags.Instance | BindingFlags.Public;
var dataProperties = typeof(myParentObject).GetProperties(bindingFlag);
Then I'm iterating through the list and retrieving the value for each property.
I've come across two different approaches to doing this, and just wondered what the difference is between them:
1)
object propertyValue开发者_JAVA百科 = property.GetGetMethod().Invoke(myObject, null);
2)
object propertValue = property.GetValue(myObject, null)
In fact, there is no difference. You can see the implementation of GetValue using 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);
}
The actual type here is RuntimePropertyInfo (PropertyInfo is an abstract class that does not provide implementation for GetValue).
精彩评论