我是否可以序列化可序列化对象的通用列表,而无需指定其类型.
像下面破坏的代码背后的意图:
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) 我正在反序列化一个名为Method.NET Serialization 的类.Method包含实现的对象列表IAction.我最初使用该[XmlInclude]属性来指定实现的所有类IAction.
但是现在,我想改变我的程序来加载目录中的所有dll并删除实现的类IAction.然后,用户可以反序列化包含其实施的操作的文件IAction.
我不再控制实现的类IAction,因此我无法使用[XmlInclude].
有没有办法在运行时设置此属性?或者为实现类设置了类似的属性?
public class Method
{
public List<Actions.IAction> Actions = new List<Actions.IAction>();
}
public interface IAction
{
void DoExecute();
}
public static Type[] LoadActionPlugins(string pluginDirectoryPath)
{
List<Type> pluginTypes = new List<Type>();
string[] filesInDirectory = Directory.GetFiles(pluginDirectoryPath, "*.dll", SearchOption.TopDirectoryOnly);
foreach (string pluginPath in filesInDirectory)
{
System.Reflection.Assembly actionPlugin = System.Reflection.Assembly.LoadFrom(pluginPath);
Type[] assemblyTypes = actionPlugin.GetTypes();
foreach (Type type in assemblyTypes)
{
Type …Run Code Online (Sandbox Code Playgroud)