gpt4 book ai didi

c# - 不使用 XmlInclude 进行序列化

转载 作者:可可西里 更新时间:2023-11-01 08:22:21 25 4
gpt4 key购买 nike

我正在使用 .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();
}

最佳答案

XmlSerializer 有一个构造函数,它接受反序列化时将接受的类型数组:

public XmlSerializer(
Type type,
Type[] extraTypes
);

您应该能够将您的 assemblyTypes 数组作为第二个参数传递。

关于c# - 不使用 XmlInclude 进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/370291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com