繁体   English   中英

序列化具有不同属性名称的Abstract类

[英]Serialize Abstract class with different attribute name

在导出流程上,我有一些XML元素表示相同的内容,但名称不同。 我无法更改其他软件定义的名称。

我需要这样的东西:

<class1>
  <MY_FIELD></MY_FIELD>
</class1>

<class2>
  <my_field></my_field>
</class2>

由于在两个字段上需要进行的处理都是相同的,因此我想创建一个包含它的抽象类。

现在,这就是我所拥有的:

public abstract class MyAbstract
{
    [XmlAttribute("MY_FIELD")]
    public MyField {get;set;}
}

[Serializable]
public class Class1 : MyAbstract
{
}

[Serializable]
public class Class2 : MyAbstract
{
}

有没有一种方法可以在最终类( class1class2 )上指定不同的XmlAttribute ,以便我可以在MyField上设置属性?

编辑 :我正在尝试使用XmlAttributeOverrides ,这似乎做我想要的,但我不能使其工作。 我不知道我在想什么。

var myType = typeof(Class1);
var overrides = new XmlAttributeOverrides();
var attrs = new XmlAttributes
{
  XmlAttribute = new XmlAttributeAttribute("test")
};
overrides.Add(myType, "MyField",attrs);

对于串行器

var serializer = new XmlSerializer(myType, overrides);

Edit2 :最后,我最终删除了抽象类上的属性,并在每个类上添加了吸气剂以进行序列化。 这很糟糕,但我仍然希望有人能给我适当的选择。

尝试

public abstract class MyAbstract
{
    abstract public MyField {get;set;}
}

[Serializable]
public class Class1 : MyAbstract
{
    [XmlAttribute("MY_FIELD")]
    public override MyField {get;set;}
}

[Serializable]
public class Class2 : MyAbstract
{
    [XmlAttribute("my_field")]
    public override MyField {get;set;}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM