0
当前,我在根类中声明了一个迭代通过派生类的属性并使用DefaultValueAttribute描述符实例化属性的默认值。我想要做的就是将它从简单的DefaultValue扩展到XmlElement,XmlAttribute和Xml命名空间序列化中包含的一系列属性。属性 - 比较
我在扩展当前设计以处理多个属性时没有加载大量的if/then/else语句来处理各种定义的属性时遇到问题。
当前设计:
private void Initialize() {
foreach(PropertyDescriptor property in TypeDescriptor.GetProperties(this)) {
XmlElementAttribute xel = (XmlElementAttribute) property.Attributes[typeof(XmlElementAttribute)];
if(xel != null) {
this.AddElement(xel.ElementName , "");
}
DefaultValueAttribute attr = (DefaultValueAttribute) property.Attributes[typeof(DefaultValueAttribute)];
if(attr != null) {
property.SetValue(this , attr.Value);
}
}
}
建议设计:
private void Initialize() {
foreach(PropertyDescriptor property in TypeDescriptor.GetProperties(this)) {
foreach(Attribute attr in property.Attributes) {
if(attr = typeof(XmlElementAttribute)){
//do something
}else if(attr = typeof(DefaultValueAttribute)){
//do something
}
}
}
}
有趣....没有考虑使用委托框架。 – GoldBishop 2012-02-12 03:14:55