我可以序列化可序列化對象的一般列表,而無需指定它們的類型。類似于以下破損代碼背后的意圖:List<ISerializable> serializableList = new List<ISerializable>();XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType());serializableList.Add((ISerializable)PersonList);using (StreamWriter streamWriter = System.IO.File.CreateText(fileName)){ xmlSerializer.Serialize(streamWriter, serializableList);}編輯:對于那些想了解細節的人:當我嘗試運行此代碼時,它在XMLSerializer [...]行上的錯誤如下:無法序列化接口System.Runtime.Serialization.ISerializable。如果我改變了List<object>我會得到"There was an error generating the XML document."。InnerException詳細信息是"{"The type System.Collections.Generic.List1[[Project1.Person, ConsoleFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] may not be used in this context."}"人員對象定義如下:[XmlRoot("Person")]public class Person{ string _firstName = String.Empty; string _lastName = String.Empty; private Person() { } public Person(string lastName, string firstName) { _lastName = lastName; _firstName = firstName; } [XmlAttribute(DataType = "string", AttributeName = "LastName")] public string LastName { get { return _lastName; } set { _lastName = value; } } [XmlAttribute(DataType = "string", AttributeName = "FirstName")] public string FirstName { get { return _firstName; } set { _firstName = value; } }}PersonList只是一個List<Person>。不過,這只是用于測試,因此并不認為細節太重要。關鍵是我有一個或多個不同的對象,所有這些對象都是可序列化的。我想將它們全部序列化為一個文件。我認為最簡單的方法是將它們放在通用列表中,然后一次性序列化列表。但這是行不通的。我也嘗試過List<IXmlSerializable>,但是失敗了System.Xml.Serialization.IXmlSerializable cannot be serialized because it does not have a parameterless constructor.抱歉,缺少詳細信息,但是我是一位初學者,不知道需要什么詳細信息。如果人們要求更多細節,而試圖以某種方式讓我理解需要的細節或概述可能指示的基本答案,那將很有幫助。也要感謝到目前為止我得到的兩個答案-如果不理解這些主意,我本可以花更多的時間閱讀。人們在此站點上的幫助程度令人驚訝。
3 回答

慕尼黑5688855
TA貢獻1848條經驗 獲得超2個贊
如果不指定期望的類型,則無法序列化對象的集合。您必須將期望類型的列表傳遞給XmlSerializer(extraTypes參數)的構造函數:
List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());
XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
xs.Serialize(streamWriter, list);
}
如果列表中的所有對象都從同一類繼承,則還可以使用XmlInclude屬性指定所需的類型:
[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}
- 3 回答
- 0 關注
- 523 瀏覽
添加回答
舉報
0/150
提交
取消