2012-02-21 29 views
1

是這樣的可能嗎?TypeDescriptor.AddAttributes和屬性

有一個[DataContract]屬性的類。這個類有兩個屬性,一個是int,另一個是字符串。這個類有兩個不同的實例。

是否可以動態地將[DataMember]屬性分配給第一個實例的int屬性,並且只分配給第二個實例的字符串屬性?如果是這樣,你會介意提供一個片段嗎?

回答

0

不,您不能在運行時分配屬性,而不會在動態類生成時執行相當複雜的magick。

好吧,我不明白TypeDescriptor :) 所以,一般來說,你需要創建自己的ICustomTypeDescriptor和實施的GetProperties方法返回的PropertyDescriptor的(following constructor)擴展屬性陣列。

static Attribute[] AddAttribute(Attribute[] attributes, Attribute attr) { 
    Array.Resize(ref attributes, attributes.Length + 1); 
    attributes[attributes.Length - 1] = new attr; 
    return attributes; 
} 

public MyPropertyDescriptor(MemberDescriptor propDef) 
     : base(propDef, AddAttribute(propDef.Attributes, new DataMembeAttribute())) 
+0

你不明白'TypeDescriptor'。 – leppie 2012-02-21 10:45:49