2010-03-03 34 views
5

Tôi lấy một danh sách IEnumerable bất động sản thông qua mã sau:Reflection: cách khác nhau để lấy giá trị tài sản

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

Sau đó, tôi đang lặp qua danh sách và lấy giá trị cho mỗi thuộc tính.

tôi đã đi qua hai cách tiếp cận khác nhau để làm điều này, và chỉ cần tự hỏi sự khác biệt là giữa chúng:

1)

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

2)

object propertValue = property.GetValue(myObject, null) 

Trả lời

4

Trong thực tế , không có sự khác biệt. Bạn có thể thấy việc thực hiện GetValue sử dụng 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); 
} 

Loại thực tế đây là RuntimePropertyInfo (PropertyInfo là một lớp trừu tượng mà không cung cấp thực hiện cho GetValue).

Các vấn đề liên quan