2012-02-12 134 views
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 
     } 
    } 
    } 
} 

回答

1

你可以定义一个Dictionary<Type, Action<object>>(或与特定类型的类的替代object),并添加要执行的代码每种类型:

var dict = new Dictionary<Type, Action<object>>(); 
dict.Add(typeof(XmlElementAttribute), obj => 
{ 
    //do something 
}); 

现在你可以只测试一下r你的字典包含类型并执行委托:

foreach(Attribute attr in property.Attributes) 
{ 
    var attributeType = attr.GetType(); 
    if(dict.ContainsKey(attributeType)) 
    { 
    dict[attributeType](this); 
    } 
} 
+0

有趣....没有考虑使用委托框架。 – GoldBishop 2012-02-12 03:14:55