我正在尝试序列化一个虚拟订单集合,其中每个订单都包含一个产品。该系列可以很好地序列化,但是订单中的示例产品属性被遗漏了。
订单收集
[XmlRoot("Orders")]
public class OrderCollection : ICollection<Order>
{
private static List<Order> _orders;
private List<Order> Orders
{
get
{
if(_orders == null)
{
_orders = new List<Order>();
}
return _orders;
}
}
//All the ICollection functions
}
命令
public class Order
{
[XmlElement("Id")]
public int Id
{
get;
set;
}
[XmlElement("Title")]
public string Title
{
get;
set;
}
[XmlElement("IsReserved")]
public bool IsReserved
{
get;
set;
}
[XmlElement("Count")]
public int Count
{
get
{
return this.Products.Count;
}
set
{
}
}
// not serializing
[XmlElement("Product")]
public Product ProductTest
{
get
{
return new Product();
}
}
// not serializing
[XmlArray("Products")]
public ICollection<Product> Products
{
get
{
return this._products;
}
}
private List<Product> _products;
public Order()
{
var rand = new Random();
var count = rand.Next(1, 5);
this._products = new List<Product>();
for (int i = 0; i < count; i++)
{
this._products.Add(new Product());
}
}
}
产品
[Serializable]
public class Product
{
[XmlElement("Id")]
public int Id
{
get;
set;
}
[XmlElement("Title")]
public string Title
{
get;
set;
}
public Product()
{
var rand = new Random();
this.Id = rand.Next(100, 9999);
this.Title = "Product " + this.Id;
}
}
输出
<?xml version="1.0"?>
<Orders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Order>
<Id>619883</Id>
<Title>Order 619883</Title>
<IsReserved>false</IsReserved>
<Count>3</Count>
</Order>
<Order>
<Id>961448</Id>
<Title>Order 961448</Title>
<IsReserved>false</IsReserved>
<Count>3</Count>
</Order>
<Order>
<Id>483677</Id>
<Title>Order 483677</Title>
<IsReserved>false</IsReserved>
<Count>2</Count>
</Order>
<Order>
<Id>512026</Id>
<Title>Order 512026</Title>
<IsReserved>false</IsReserved>
<Count>2</Count>
</Order>
<Order>
<Id>916029</Id>
<Title>Order 916029</Title>
<IsReserved>false</IsReserved>
<Count>4</Count>
</Order>
<Order>
<Id>109800</Id>
<Title>Order 109800</Title>
<IsReserved>false</IsReserved>
<Count>4</Count>
</Order>
</Orders>
我完全感到困惑。深度序列化似乎正在工作,因为否则订单不会在 OrderCollection 中序列化,但随后它就会停止。有什么建议吗?