不同类的属性之间的属性采取以下示例代码:如何共享
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>
的子元素。元素可以以任何顺序排列,顺序很重要。另外,将来可能会有更多的子元素。由于需要为属性保留两个单独的位置,因此目前编码的方式会使维护变得繁琐且容易出错。
有没有办法让这两个属性“共享”这些属性,这样一次编辑就会影响到它们两个呢?我尝试了以下内容:
public class CommomAttribute : Attribute
{
public XmlElementAttribute f = new XmlElementAttribute("element-one", typeof(ElementOne));
public XmlElementAttribute l = new XmlElementAttribute("element-two", typeof(ElementTwo));
}
然后,我用一个[Command]替换上述类属性的冗余属性。这没有奏效。
另一个问题:有没有更好的方法来解决这个问题?
这是一种可能性。我确实可以控制xml格式。不过,如果我不必这样做,那会很好,因为它使xml变得有点丑陋。 – josmith42