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

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

下面是一段示例代码来解释我的问题:

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

我知道如何使用 [XmlElement( ElementName = "DesiredVarName")] 在相同的 class 中执行此操作,但想知道是否可以在派生的 class 中执行此操作全部?如果是,如何?

想到的一件事是使用 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);

在此示例中,我们以编程方式将要应用的自定义序列化属性列表传递给 XmlSerializer。

从您的评论来看,您似乎可以对 TheBaseClass 进行更改。因此,您可以在基础 class 和 return true 中为 BaseClassList 属性 添加虚拟 bool ShouldSerialize{PropertyName}() 方法。然后在派生的 class 和 return 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; }
}

有关此方法为何有效的解释,请参阅 Defining Default Values with the ShouldSerialize and Reset Methods