0

我已经从代码项目中获取了代码set。我试图使属性Phone只读,如果QRType不等于ContactPhone(QRType 是一个枚举):

public QRType Type 
{ 
    get { return type; } 
    set 
    { 
        type = value;
        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(GetType())["Phone"];
        ReadOnlyAttribute attribute = (ReadOnlyAttribute)
            descriptor.Attributes[typeof(ReadOnlyAttribute)];
        FieldInfo fieldToChange = attribute.GetType().GetField("isReadOnly",
                                                 BindingFlags.NonPublic |
                                                 BindingFlags.Instance);

        bool v = (type != QRType.Contact && type != QRType.Phone);
        fieldToChange.SetValue(attribute, v );       
    }
}

上面的代码不能正常工作,电话字段总是灰显,同时设置如下值:

fieldToChange.SetValue(attribute, true );
fieldToChange.SetValue(attribute, false );

两者都正常工作。它有什么问题?

更新: 有趣的是,不使用&&它可以工作:

fieldToChange.SetValue(attribute, type != QRType.Contact);
4

0 回答 0