我使用.NET序列化反序列化名为Method
的类。 Method
包含实施IAction
的对象列表。我最初使用[XmlInclude]
属性来指定实现IAction
的所有类。序列化无XmlInclude
但现在,我想改变我的程序加载所有的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();
}