简体   繁体   English

C#,为什么XmlSerializer序列化基础对象而不是接口?

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

Why does XmlSerializer serialize ALL of Car when serializing ICar ? 为什么XmlSerializer在序列化ICar时序列化所有Car ..instead of just serializing A from ICar ? ..而不仅仅是从ICar序列化A

I find this odd because when I watch this in the debugger, icars only contains A , but test.xml has A , B and C . 我发现这很奇怪,因为当我在调试器中看到它时, icars只包含A ,但test.xmlABC

Example code: 示例代码:

//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 Results: XML结果:

<Cars>
    <A>Car A</A>
    <B>Car B</B>
    <C>Car C</C>
<Cars>

Was expecting to get this (but didn't): 期待得到这个(但没有):

<Cars>
    <A>Car A</A>
<Cars>

Because you created XmlSerializer passing typeof(Cars) to it's constructor. 因为您创建了XmlSerializertypeof(Cars)传递给它的构造函数。 XmlSerializer will not work on interface types. XmlSerializer不适用于接口类型。

If you want to ignore some Fields, you can use System.Xml.Serialization.XmlIgnoreAttribute in your class. 如果要忽略某些字段,可以在类中使用System.Xml.Serialization.XmlIgnoreAttribute See this post . 这篇文章

You can't deserialize to ICar , so why would you expect to serialize from ICar ? 你不能反序列化到ICar ,那么为什么你期望从ICar序列化?

Just make a simple type that does what you need. 只需制作一个能满足您需求的简单类型。

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