我是否可以序列化可序列化对象的通用列表,而无需指定其类型.
像下面破坏的代码背后的意图:
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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
对于那些想要了解详细信息的人:当我尝试运行此代码时,它在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."}"
person对象定义如下:
[XmlRoot("Person")]
public class Person
{
string _firstName = String.Empty;
string _lastName = String.Empty;
private Person()
{
}
public Person(string lastName, string firstName)
{
_lastName = lastName;
_firstName …Run Code Online (Sandbox Code Playgroud)