[英]Why does XmlSerializer serialize an object to a file containing zeros instead of XML?
[英]C#, Why does XmlSerializer serialize the base object instead of the Interface?
為什么XmlSerializer
在序列化ICar
時序列化所有Car
? ..而不僅僅是從ICar
序列化A
?
我發現這很奇怪,因為當我在調試器中看到它時, icars
只包含A
,但test.xml
有A
, B
和C
示例代碼:
//IMPLEMENTATION
Cars cars = new Cars();
ICars icars = cars;
var iXmls = new XmlSerializer(typeof(Cars));
using (TextWriter iTw = new StreamWriter("test.xml"))
{
iXmls.Serialize(iTw, icar);
}
//CLASS
[XmlRootAttribute("Cars")]
public class Cars : ICar
{
private string _A = "Car A";
private string _B = "Car B";
private string _C = "Car C";
public string A { /* get.. set.. */}
public string B { /* get.. set.. */}
public string C { /* get.. set.. */}
}
//INTERFACE
public interface ICars
{
string A;
}
XML結果:
<Cars>
<A>Car A</A>
<B>Car B</B>
<C>Car C</C>
<Cars>
期待得到這個(但沒有):
<Cars>
<A>Car A</A>
<Cars>
因為您創建了XmlSerializer
將typeof(Cars)
傳遞給它的構造函數。 XmlSerializer不適用於接口類型。
如果要忽略某些字段,可以在類中使用System.Xml.Serialization.XmlIgnoreAttribute
。 看這篇文章 。
你不能反序列化到ICar
,那么為什么你期望從ICar
序列化?
只需制作一個能滿足您需求的簡單類型。
public class PlainOldCar : ICar
{
public string A {get;set;}
public PlainOldCar(ICar carSource) //copy constructor
{
this.A = carSource.A;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.