2012-02-21 108 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