2013-05-12 41 views
5

我不知道這是什麼意思了。該documentation不是很清楚:什麼是getfield命令,SetField,getProperty和的SetProperty中的BindingFlags枚舉?

getfield命令指定應返回指定字段的值。

SetField指定應設置指定字段的值。

GetProperty指定應返回指定屬性的值。

SetProperty指定應該設置指定屬性的值。對於COM屬性,指定此綁定標誌等同於指定PutDispProperty和PutRefDispProperty。

如果我在BindingFlags枚舉中指定他們,他們應該返回什麼?我認爲它有屬性和類型的字段做的,但這個簡單的測試說不:

class Base 
{ 
    int i; 
    int I { get; set; } 

    void Do() 
    { 

    } 
} 

print typeof(Base).GetMembers(BindingFlags.GetField 
           | BindingFlags.Instance 
           | BindingFlags.NonPublic); 

// Int32 get_I() 
// Void set_I(Int32) 
// Void Do() 
// Void Finalize() 
// System.Object MemberwiseClone() 
// Int32 I 
// Int32 i 
// Int32 <I>k__BackingField 

同一組則返回SetFieldGetPropertySetProperty

回答

6

所有這些都沒有必要一一列舉,而是正確地訪問性能。例如,要在給定實例上設置屬性的值,您需要SetProperty標誌。

Base b; 

typeof(Base).InvokeMember("I", 
    BindingFlags.SetProperty|BindingFlags.Public|BindingFlags.Instance, 
    ..., 
    b, new object[] { newvalue }); 

但要獲得這個屬性的值,你就需要使用getProperty: 標誌。

Base b; 

int val = (int)typeof(Base).InvokeMember("I", 
    BindingFlags.GetProperty|BindingFlags.Public|BindingFlags.Instance, 
    ..., 
    b, null); 
+0

哦,我看;混亂看到同一組中使用的標誌'GetMembers' .. – nawfal 2013-05-12 07:05:11

+0

同意,可能是一種混亂。 – 2013-05-12 07:11:21