2010-03-20 214 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時,結果是整個類變爲只讀。