简体   繁体   中英

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

Why does XmlSerializer serialize ALL of Car when serializing ICar ? ..instead of just serializing A from ICar ?

I find this odd because when I watch this in the debugger, icars only contains A , but test.xml has A , B and C .

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:

<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. XmlSerializer will not work on interface types.

If you want to ignore some Fields, you can use System.Xml.Serialization.XmlIgnoreAttribute in your class. See this post .

You can't deserialize to ICar , so why would you expect to serialize from 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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM