gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:39 26 4
gpt4 key购买 nike

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

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")] 当变量在同一个类中时执行此操作,但想知道是否可以在派生中执行此操作上课吗?如果是,如何?

最佳答案

从您的评论来看,您似乎能够对 TheBaseClass 进行更改。因此你可以添加一个虚拟 bool ShouldSerialize{PropertyName}()基类中 BaseClassList 属性的方法并返回 true。然后在派生类中覆盖它并返回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 .

关于c# - 如何在派生类中序列化具有不同名称的基类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36688707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com