【发布时间】:2010-09-27 02:01:32
【问题描述】:
我正在使用 .NET 序列化反序列化一个名为 Method 的类。 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 foundInterface = type.GetInterface("IAction");
if (foundInterface != null)
{
pluginTypes.Add(type);
}
}
}
return pluginTypes.Count == 0 ? null : pluginTypes.ToArray();
}
【问题讨论】:
标签: c# xml reflection serialization