简体   繁体   English

如何在派生类中序列化具有不同名称的基类变量

[英]how to serialize a base class variable with a different name in a derived class

Here is a piece of sample code to explain my question:这是一段示例代码来解释我的问题:

public class TheBaseClass 
{
   public list<int> BaseClassList {get; set;}
}

public class TheDerivedClass : TheBaseClass
{
   //here I want to indicate the XmlSerializer to serialize the 'BaseClassList' with a different name 'DerivedClassList'
}

I know how to do this when the variable is in the same class by using [XmlElement( ElementName = "DesiredVarName")] but want to know if it is possible to do this in a derived class at all?我知道如何通过使用[XmlElement( ElementName = "DesiredVarName")]当变量在同一个类中时执行此操作,但想知道是否可以在派生类中执行此操作? If yes, how?如果是,如何?

From your comment, it appears you are able to make changes to TheBaseClass .根据您的评论,您似乎可以对TheBaseClass进行更改。 Thus you can add a virtual bool ShouldSerialize{PropertyName}() method for the BaseClassList property in the base class and return true .因此,您可以为基类中的BaseClassList属性添加一个虚拟bool ShouldSerialize{PropertyName}()方法并返回true Then override it in the derived class and return false , and introduce a proxy property with the desired name:然后在派生类中覆盖它并返回false ,并引入一个具有所需名称的代理属性:

public class TheBaseClass
{
    public List<int> BaseClassList { get; set; }

    public virtual bool ShouldSerializeBaseClassList() { return true; }
}

public class TheDerivedClass : TheBaseClass
{
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public List<int> DerivedClassList { get { return BaseClassList; } set { BaseClassList = value; } }

    public override bool ShouldSerializeBaseClassList() { return false; }
}

For an explanation of why this works see Defining Default Values with the ShouldSerialize and Reset Methods .有关为何如此有效的解释,请参阅使用 ShouldSerialize 和 Reset 方法定义默认值

One thing that comes to mind is to use XmlAttributeOverrides :想到的一件事是使用XmlAttributeOverrides

var attributes = new XmlAttributes();
attributes.XmlElements.Add(new XmlElementAttribute("DerivedClassList"));
var overrides = new XmlAttributeOverrides();
overrides.Add(typeof(TheBaseClass), "BaseClassList", attributes);

var serializer = new XmlSerializer(typeof(TheDerivedClass), overrides);

In this example we are programatically passing to the XmlSerializer a list of custom serialization attributes that will be applied.在此示例中,我们以编程方式向 XmlSerializer 传递将应用的自定义序列化属性列表。

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

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