0

采取以下示例代码:

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;}
}

onElementOne.SubElementsElementTwo.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] 替换了上述类属性上的冗余属性。这没有用。

另一个问题:有没有更优雅的方法来解决这个问题?

4

2 回答 2

1

如果您不介意更深入地了解子元素项,您可以试试这个:

public abstract class ElementBase
{
}

public class ElementOne : ElementBase
{
}

public class ElementTwo : ElementBase
{
    public SubElementList SubElements { get; set; }
}

public class SubElementList
{
    [XmlElement("element-one", typeof(ElementOne))]
    [XmlElement("element-two", typeof(ElementTwo))]
    public ElementBase[] Items { get; set; }
}

[XmlRoot("root-element")]
public class RootElement
{
    public SubElementList SubElements { get; set; }
}
于 2012-06-29T15:28:42.653 回答
0

在我的脑海中,我会做以下事情:

  1. 在每个类(一和二)的 ctor 上,需要 ElementBase 的实例并将其保留为私有属性(例如,“SyncingElement”)
  2. 修改SubElements的setter,与“SyncingElement”的实例同步

这样,两个对象上的子元素将具有相同的内存地址(相同的实例)。因此,如果有人从 One 获取 SubElements 的实例修改了索引 [2] 处的对象(例如),它也会影响位于 Two 的 SubElements。

于 2012-06-29T13:57:48.700 回答