没有序列化XmlInclude [英] Serializing without XmlInclude
问题描述
我反序列化使用.NET序列化名为方法
类。 方法
包含 IAction
实施对象的列表。我原来使用的 [XmlInclude]
属性来指定执行 IAction
所有类。
但现在,我想改变我的程序加载目录中的所有DLL的并去掉其实现类 IAction
。然后,用户可以反序列化包含他们的行动实施 IAction
文件。
我不控制实现了这个类 IAction
了,所以我不能使用的 [XmlInclude]
有没有办法在运行时设置该属性? ?或者有类似属性的实现类设置
public类方法
{
公开名单< Actions.IAction>操作=新的List< Actions.IAction>();
}
公共接口IAction
{
无效DoExecute();
}
公共静态类型[] LoadActionPlugins(字符串pluginDirectoryPath)
{
名单,LT;类型> pluginTypes =新的List<类型和GT;();
的String [] = filesInDirectory Directory.GetFiles(pluginDirectoryPath,* .DLL,SearchOption.TopDirectoryOnly);
的foreach(在filesInDirectory串pluginPath)
{
System.Reflection.Assembly actionPlugin = System.Reflection.Assembly.LoadFrom(pluginPath);
类型[] = assemblyTypes actionPlugin.GetTypes();
的foreach(在assemblyTypes型型)
{
型foundInterface = type.GetInterface(IAction);
如果(foundInterface!= NULL)
{
pluginTypes.Add(类型);
}
}
}
返回pluginTypes.Count == 0?空:pluginTypes.ToArray();
}
XmlSerializer的具有接受一个构造函数类型的数组反序列化时将被接受:
公开的XmlSerializer($ b $型b型,
型[] extraTypes
);
您应该能够通过你的assemblyTypes作为第二个参数的数组。
I'm deserializing a class called Method
using .NET Serialization. Method
contains a list of objects implementing IAction
. I originally used the [XmlInclude]
attribute to specify all classes which implement IAction
.
But now, I'd like to change my program to load all the dll's in a directory and strip out the classes which implement IAction
. Then users can deserialize files which contain their actions implementing IAction
.
I don't control the classes which implement IAction
anymore, therefore I can't use [XmlInclude]
.
Is there a way to set this attribute at runtime? Or have a similar attribute set for the implementing class?
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 foundInterface = type.GetInterface("IAction");
if (foundInterface != null)
{
pluginTypes.Add(type);
}
}
}
return pluginTypes.Count == 0 ? null : pluginTypes.ToArray();
}
XmlSerializer has a constructor that accepts an array of types that will be accepted when deserializing:
public XmlSerializer(
Type type,
Type[] extraTypes
);
You should be able to pass your array of assemblyTypes as the second argument.
这篇关于没有序列化XmlInclude的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!