动态移除C#属性中的属性特性

14

我有一个包含以下属性的类。

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

    [Category("Contact Info")]
    public string Name{ get; set; }
}

这个类的对象被分配给一个属性网格,以便用户可以更新现有联系人。您可以看到手机被标记为只读。

但是,当我想要添加一个全新的联系人时,我希望用户也能够编辑该联系人的电话号码。为此,我需要在将对象分配给属性网格之前动态地从类型中删除“只读”属性。这是否可能?

6个回答

11

4
链接无法访问,显示"404未找到"。 - Pang
1
链接已失效。 - Chase Florell
该文章可通过Waback Machine获取:https://web.archive.org/web/20190907182632/http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html - basiphobe

2

我必须同意Omu的观点;在这种情况下,您实际上是在谈论两个类(视图模型),以支持您的两个不同视图。可以考虑使用

创建联系人视图模型(CreateContactViewModel)和编辑联系人视图模型(EditContactViewModel)


2

CodingLight.com博客已经迁移到blogspot(上面的链接已经失效)。 请参见http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html

此外,SysAdmin的跟进并没有提到[RefreshProperties(RefreshProperties.All)]属性,这似乎是一个实际可行的解决方案所必需的。

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


3
新链接也不可用。 - Jacques Bosch

1

目前无法在运行时动态删除属性。

作为建议,您可以创建两个类:一个带有属性,一个不带属性。


1
不需要创建两个类,可以使用反射来修改 ReadOnly 属性的布尔字段并将其更改为 false(非只读)。 - andreialecu

0

我跟进了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);
        }
}

我认为虽然这个可以工作,但它不是一个好的设计。责任混乱不清。 - Paul

0

原始的“链接”显示如下:

enter image description here

现在链接不会再次中断。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接