动态删除属性的C#属性

我有一组具有一组属性的类如下所示。

class ContactInfo { [ReadOnly(true)] [Category("Contact Info")] public string Mobile { get; set; } [Category("Contact Info")] public string Name{ get; set; } } 

此类的对象被分配给属性网格,以便用户可以更新现有联系人 。 你可以看到Mobile被标记为ReadOnly。

但是,当我想添加一个全新的联系人时 ,我希望用户能够编辑联系人移动设备。 为此,我需要在将对象分配给属性网格之前从Type中动态删除Readonly属性 。 可能吗?

您无法在运行时删除该属性,但可以使用reflection将ReadOnly属性的ReadOnly专用支持字段更改为False。 使它相当于[ReadOnly(false)]

有关详细信息,请参阅此文

http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html

编辑:固定链接

我必须同意Omu; 在这种情况下,你真的在​​谈论两个类(视图模型),以支持你的两个不同的视图。 就像是

CreateContactViewModel和EditContactViewModel

目前不可能以dinamycally方式删除属性(在运行时)

作为建议你可以做两个类:一个有属性,一个没有

我跟进了Legenden的建议。 这就是我想出的

 class ContactInfo { [ReadOnly(true)] [Category("Contact Info")] public string Mobile { get; set; } [Category("Contact Info")] public string Name{ get; set; } public void SetMobileEdit(bool allowEdit) { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(this.GetType())["Mobile"]; ReadOnlyAttribute attrib = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)]; FieldInfo isReadOnly = attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance); isReadOnly.SetValue(attrib, !allowEdit); } } 

CodingLight.com博客转移到blogspot(以上链接已损坏)。 请参阅http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html 。

此外,SysAdmin的后续内容没有提到实际工作解决方案似乎必需的[RefreshProperties(RefreshProperties.All)]属性。

最后,我相信即使David Morton(引用文章的作者)也错过了一件非常重要的事情:如果类( ContactInfo ,在SysAdmin的后续示例中)没有至少一个具有在编译时定义的[ReadOnly]属性的属性,然后当“isReadOnly”FieldInfo在运行时设置为true时,结果是整个类变为只读。