2012-02-12 12 views
0

現在、私は、派生クラスのプロパティを反復し、DefaultValueAttribute記述子を使用してプロパティのDefault Valueをインスタンス化するルートクラスの宣言を持っています。私がしたいのは、これを単に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 
}); 

これで、あなたの辞書には型が入っており、デリゲートを実行します:

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

おもしろいことに、デリゲートフレームワークの使用については考えませんでした。 – GoldBishop

関連する問題