小编Ken*_*Ken的帖子

使用.NET的XmlSerializer时忽略派生类的属性

我有一个基类,它有一个虚拟属性和一个覆盖虚拟属性的派生类型.该类型可以序列化为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)

.net virtual inheritance overriding xmlserializer

7
推荐指数
1
解决办法
2425
查看次数

标签 统计

.net ×1

inheritance ×1

overriding ×1

virtual ×1

xmlserializer ×1