gpt4 book ai didi

c# - DataContract 序列化抽象类

转载 作者:太空狗 更新时间:2023-10-29 21:30:40 26 4
gpt4 key购买 nike

我有一个接口(interface) IServiceInfo 和一个抽象类 ServiceInfo。有几个继承自 ServiceInfo 的类,如 CoreServiceInfo、ModuleServiceInfo 等。有一个名为 RootService 的服务契约返回 IServiceInfo。

 public IServiceInfo GetServiceInfo()
{
return (IServiceInfo)new CoreServiceInfo();
}

我在序列化时遇到问题。我可以使用 ServiceKnownType 来标识基类,并使用 KnownType 来标识子类。

问题是我不知道所有的 ServiceInfo 子项,因为应用程序可以有从 ServiceInfo 继承的不同子项的插件,所以我不能告诉序列化器在序列化的 XML 中有所有的子项。

我可以忽略抽象类,但它包含某些通用实现,所以我需要保留它。作为解决方法,我可以让另一个类说“sampleServiceInfo”并将所有信息类转换为 sampleServiceInfo 并从 Service 方法返回它,并将 KnownType 定义为 ServiceInfo 类。

[KnownType(typeof(sampleServiceInfo))]
public class ServiceInfo : IServiceInfo

但这听起来不太好。请建议。我需要编写自定义序列化程序吗?有什么方法可以仅序列化基并在两者具有相同成员时忽略子项吗?

最佳答案

获取实现给定抽象类或接口(interface)的所有已加载程序集中的所有类型(引用:Implementations of interface through Reflection)

 var allTypes =  AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => typeof(A).IsAssignableFrom(type));

然后创建序列化程序,将 allTypes 作为已知类型参数传递,如下所示

var serializer = new DataContractSerializer(typeof(A), allTypes);

就是这样 - 您将能够序列化和反序列化派生自 A 的任何类型(A 可以是类或接口(interface),如果是接口(interface),序列化程序将元素写入派生自 xs:anyType。

关于c# - DataContract 序列化抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4495887/

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