属性 - 比较

时间:2012-02-12 02:42:25

标签: c# attributes

目前,我在根类中有一个声明,它使用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 个答案:

答案 0 :(得分:1)

您可以定义Dictionary<Type, Action<object>>(或使用您的类的特定类型替换object)并添加您要为每种类型执行的代码:

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

现在您可以测试您的字典是否包含类型并执行委托:

foreach(Attribute attr in property.Attributes) 
{  
   var attributeType = attr.GetType();
   if(dict.ContainsKey(attributeType))
   {
     dict[attributeType](this);
   }
}
相关问题