c# – 當一個類繼承自List
ItemType>,但是當我這樣做時,XmlSerializer不會序列化在我的類中宣告的任何屬性或欄位,下面的示例演示:
public partial class Form1 : Form { public Form1() { InitializeComponent(); DoSerialize(); } private void DoSerialize() { MyClass obj = new MyClass(); obj.Add(1); obj.Add(2); obj.Add(3); XmlSerializer s = new XmlSerializer(typeof(MyClass)); StringWriter sw = new StringWriter(); s.Serialize(sw, obj); } } [Serializable] [XmlRoot] public class MyClass : List<int> { public MyClass() { } int myAttribute = 2011; [XmlAttribute] public int MyAttribute { get { return myAttribute; } set { myAttribute = value; } } }
生成的XML:
<?xml version="1.0" encoding="utf-16"?> <ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <int>1</int> <int>2</int> <int>3</int> </ArrayOfInt>
:
-
Classes that implement ICollection or IEnumerable. Only collections are
serialized, not public properties.
(檢視“可序列化的專案”部分).Someone has filed a bug against this, but it won’t be changed – 這裡,Microsoft還確認,不包括實現ICollection的類的屬性實際上是XmlSerializer的行為.
解決辦法是:
實現IXmlSerializable並自己控制序列化.
要麼
>更改MyClass,使其具有List型別的公共屬性(並且不要對其進行子類化).
要麼
>使用DataContractSerializer來處理這種情況.
http://stackoverflow.com/questions/5069099/when-a-class-is-inherited-from-list-xmlserializer-doesnt-serialize-other-att