[英]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.xml
有A
, B
和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: 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. 因为您创建了
XmlSerializer
将typeof(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.