次のサンプルコードを見てください。
public abstract class ElementBase
{
}
public class ElementOne : ElementBase
{
}
public class ElementTwo : ElementBase
{
[XmlElement("element-one", typeof(ElementOne))]
[XmlElement("element-two", typeof(ElementTwo))]
public ElementBase[] SubElements { get; set; }
}
[XmlRoot("root-element")]
public class RootElement
{
[XmlElement("element-one", typeof(ElementOne))]
[XmlElement("element-two", typeof(ElementTwo))]
public ElementBase[] SubElements { get; set;}
}
上の属性ElementOne.SubElements
とElementTwo.SubElements
同期を維持する必要があります(つまり、一方に追加された属性はもう一方に追加される必要があり、引数は同じままである必要があります)。これは、xmlで<element-one>
、要素が両方とも次のように表示される可能性があるためです。<root-element>
およびへのサブ要素<element-two>
。要素は任意の順序にすることができ、順序は重要です。また、将来的にはさらに多くのサブ要素が存在する可能性があります。現在コーディングされている方法では、属性用に2つの別々の場所を維持する必要があるため、メンテナンスが面倒でエラーが発生しやすくなります。
これらの属性を2つのプロパティ間で「共有」して、1回の編集で両方に影響を与える方法はありますか?私は次のことを試しました:
public class CommomAttribute : Attribute
{
public XmlElementAttribute f = new XmlElementAttribute("element-one", typeof(ElementOne));
public XmlElementAttribute l = new XmlElementAttribute("element-two", typeof(ElementTwo));
}
次に、上記のクラスのプロパティの冗長な属性を1つの[コマンド]に置き換えました。これはうまくいきませんでした。
別の質問:この問題を解決するためのよりエレガントな方法はありますか?