这样的事情可能吗?
有一个具有[DataContract]属性的类。该类有两个属性,一个是int,另一个是string。这个类有两个不同的实例。
是否可以动态地将[DataMember]属性分配给第一个实例的int属性,而只分配给第二个实例的字符串属性?如果是这样,你介意提供一个片段吗?
答案 0 :(得分: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()))