BindingFlags枚举中的GetField,SetField,GetProperty和SetProperty是什么?

naw*_*fal 5 .net reflection propertyinfo fieldinfo

我不知道这是为了什么.该文件是不是很清楚:

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
Run Code Online (Sandbox Code Playgroud)

返回相同的集合SetField,GetPropertySetProperty.

Wik*_*hla 6

所有这些都不需要枚举,而是正确访问属性.例如,要在给定实例上设置属性的值,您需要SetProperty标志.

 Base b;

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

但要获取此属性的值,您需要使用GetProperty:标志.

 Base b;

 int val = (int)typeof(Base).InvokeMember( "I", 
     BindingFlags.GetProperty|BindingFlags.Public|BindingFlags.Instance,
     ...,
     b, null);
Run Code Online (Sandbox Code Playgroud)