2010-03-20 216 views
9

我有一组属性,如下所示。动态删除属性的C#属性

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

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

这个类的对象被分配到一个属性网格,从而使用户可以更新现有的接触。你可以看到Mobile被标记为ReadOnly。

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

回答

7

不能删除在运行时的属性,但你可以使用反射只读属性的只读私人支持字段更改为False。使得它相当于[只读(假)]

请参阅本文的详细信息:

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

编辑:固定链接

+0

这正是我想要的情况。 – SysAdmin 2010-03-20 13:42:17

+0

链接已死。 – grimmig 2011-06-20 11:56:41

+0

@grimmig:固定链接 – andreialecu 2011-07-04 17:58:11

1

它不可能在一瞬间dinamycally删除属性(在运行时)

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

+1

无需制作2个类,反射可用于修改ReadOnly属性的布尔值字段并将其更改为false(不是只读)。 – andreialecu 2010-03-20 13:37:05

+0

嗯,良好的通话,我没有想过:) – Omu 2010-03-20 20:13:00

2

我不得不同意瓦特/雄武;在这种情况下,你真的谈论两个类(视图模型),以支持你的两种不同的观点。喜欢的东西

CreateContactViewModel和EditContactViewModel

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); 
     } 
} 
+0

我认为这虽然有效,但这不是一个好设计。责任在流血。 – Paul 2010-03-20 13:58:20

0

CodingLight.com博客移动到blogspot(上面的链接已损坏)。 见http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html

此外,SysAdmin的跟进没有提及[RefreshProperties(RefreshProperties.All)]属性,这似乎是实际工作的解决方案所必需的。

最后,我认为,即使大卫·莫顿(所引用的文章的作者)错过了一个非常重要的事情:如果类(ContactInfo,在系统管理员的后续例子)没有至少,并定义了[ReadOnly]属性一个属性在编译时,那么当在运行时将“isReadOnly”FieldInfo设置为true时,结果是整个类变为只读。