2010-07-12 41 views
0

我需要在運行時爲某個屬性添加屬性(用於設計時)。我知道我可以這樣做類:在運行時爲屬性添加屬性(用於設計時間目的)

TypeDescriptor.AddAttributes(typeof(MyType), new MyRuntimeAttribute());

但我找不到任何方法來做同樣的屬性。

有什麼建議嗎?

UPD:完全相同任務如下:

public class BaseClass { 
    public BaseClass(string name) { Name = name; } 
    public Name { get; set; } 
} 
public class Descendant1: BaseClass { 
    public Descendant1() : base("Default Name 1") { } 
} 
... 
public class DescendantN: BaseClass { 
    public DescendantN() : base("Default Name N") { } 
}

我希望每個子孫讓每個自己的DefaultValueAttribute在與相應的默認名稱的名稱屬性。而且我不想在每個下降點上對DefaultValueAttribute進行硬編碼:)

+0

beresta berestnul! – amartynov 2010-07-14 11:49:34

回答

1

您無法動態添加或刪除屬性。請注意,TypeDescriptor實際上並沒有爲該類添加屬性:如果在使用MyRuntimeAttribute附加屬性後檢查typeof(MyType).GetCustomAttributes(false)返回的數組,您將注意到它不屬於它。

既然你提到設計時,你可以做的是動態修改屬性。那是你真正想要做什麼?

參見:

+0

對不起,但沒有。 我剛纔調查了一下,現在我認爲用GetProperties覆蓋的TypeConverter實現是我需要的(PropertyDescriptorAdaptor將返回基於http://msdn.microsoft.com/en-us/library/system的修改後的AttributesCollection。 componentmodel.propertydescriptor.aspx文章)。我會在一些測試後在這裏發佈結果。 不過,謝謝你的第二個鏈接,回帖裏有個很有意思的帖子。 – Beresta 2010-07-12 18:51:33

相關問題