【问题标题】:Remove C# attribute of a property dynamically动态删除属性的 C# 属性
【发布时间】:2011-01-29 19:12:20
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: c# .net propertygrid


    【解决方案1】:

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

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

    【讨论】:

    • 不需要做2个类,反射可以修改ReadOnly属性的布尔字段,修改为false(非只读)。
    【解决方案2】:

    我必须同意 Omu;在这种情况下,您实际上是在谈论两个类(视图模型),以支持您的两个不同视图。类似的东西

    CreateContactViewModel 和 EditContactViewModel

    【讨论】:

      【解决方案3】:

      您不能在运行时删除该属性,但可以使用反射将 ReadOnly 属性的 ReadOnly 私有支持字段更改为 False。使其等同于 [ReadOnly(false)]

      详情请看这篇文章:

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

      编辑:固定链接

      【讨论】:

      • 答案中的链接已失效 - "404 Not Found".
      【解决方案4】:

      我遵循了 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);
              }
      }
      

      【讨论】:

      • 我认为虽然这可行,但它不是一个好的设计。责任在流血。
      【解决方案5】:

      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 时,结果是整个类变为只读。

      【讨论】:

      • 新链接也坏了。
      猜你喜欢
      • 2020-07-08
      • 2016-08-25
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      相关资源
      最近更新 更多