Question

I have no idea what these are for. The documentation is not very clear:

GetField Specifies that the value of the specified field should be returned.

SetField Specifies that the value of the specified field should be set.

GetProperty Specifies that the value of the specified property should be returned.

SetProperty Specifies that the value of the specified property should be set. For COM properties, specifying this binding flag is equivalent to specifying PutDispProperty and PutRefDispProperty.

If I specify them in BindingFlags enumeration, what should they return? I thought it has to do with properties and fields of a type, but this simple test says no:

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

The same set is returned for SetField, GetProperty and SetProperty.

Was it helpful?

Solution

All of these are not needed to enumerate but rather to access properties properly. For example, to set a value of the property on given instance, you need SetProperty flag.

 Base b;

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

but to get the value of this property, you would need to use the GetProperty: flag.

 Base b;

 int val = (int)typeof(Base).InvokeMember( "I", 
     BindingFlags.GetProperty|BindingFlags.Public|BindingFlags.Instance,
     ...,
     b, null);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top