我有一个基类,它有一个虚拟属性和一个覆盖虚拟属性的派生类型.该类型可以序列化为XML.我想要做的是当对象是派生类型时,不要持久于项目列表属性.为了实现这一点,派生类用[XmlIgnore]属性修饰了重写属性.基类中的虚拟属性不应用XmlIgnore属性.由于某种原因,即使对象属于派生类型(DynamicCart),项目列表也会被序列化.
当我将XmlIgnore属性应用于基类中的虚拟属性时,列表不会被序列化为文件.
public class ShoppingCart
{
public virtual List<items> Items{get; set;}
//and other properties
public void SerializeToXML (string filePath)
{
var xmlSerializer = new XmlSerializer(this.GetType());
textWriter = new System.IO.StreamWriter(filePath);
xmlSerializer.Serialize(textWriter, this);
textWriter.Flush();
textWriter.Close();
}
}
//A cart that is populated by algo based on parameters supplied by user. I have no need to
//persist the actual items across sessions.
class DynamicCart: ShoppingCart
{
[XmlIgnore]
public override List<items>{get;set;}
//and other properties
}
class …Run Code Online (Sandbox Code Playgroud)