簡體   English   中英

C#,為什么XmlSerializer序列化基礎對象而不是接口?

[英]C#, Why does XmlSerializer serialize the base object instead of the Interface?

為什么XmlSerializer在序列化ICar時序列化所有Car ..而不僅僅是從ICar序列化A

我發現這很奇怪,因為當我在調試器中看到它時, icars只包含A ,但test.xmlABC

示例代碼:

//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>

因為您創建了XmlSerializertypeof(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM