【问题标题】:What are GetField, SetField, GetProperty and SetProperty in BindingFlags enumeration?BindingFlags 枚举中的 GetField、SetField、GetProperty 和 SetProperty 是什么?
【发布时间】:2013-05-12 06:51:05
【问题描述】:

我不知道这些是干什么用的。 documentation不是很清楚:

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 返回相同的集合。

【问题讨论】:

    标签: .net reflection propertyinfo fieldinfo


    【解决方案1】:

    所有这些都不需要枚举,而是正确访问属性。例如,要在给定实例上设置属性值,您需要 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);
    

    【讨论】:

    • 同意,可能有点令人困惑。
    猜你喜欢
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2010-10-16
    • 1970-01-01
    相关资源
    最近更新 更多