DataContract序列化抽象类

hun*_*ind 6 c# wcf serialization abstract

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

 public IServiceInfo GetServiceInfo()
 {
     return (IServiceInfo)new CoreServiceInfo();
 }
Run Code Online (Sandbox Code Playgroud)

我有序列化问题.我可以使用ServiceKnownType来标识基类,使用KnownType来标识子类.

问题是我不知道所有的ServiceInfo子节点,因为应用程序可以有从ServiceInfo继承的不同子节点的插件,所以我无法告诉序列化器将序列化XML中的所有子节点.

我可以忽略抽象类,但它包含某些常见的实现,所以我需要保留它.作为一种解决方法,我可以让另一个类说"sampleServiceInfo"并将所有info类转换为sampleServiceInfo并从Service方法返回它,并将KnownType定义为ServiceInfo类.

[KnownType(typeof(sampleServiceInfo))]
public class ServiceInfo : IServiceInfo
Run Code Online (Sandbox Code Playgroud)

但这听起来并不是很好的方式.请建议.我需要编写自定义序列化程序吗?是否有任何方法只能序列化基数并忽略孩子,当两者都有相同的成员?

Om *_*ane 7

获取实现给定抽象类或接口的所有已加载程序集中的所有类型(参考:通过Reflection实现接口)

 var allTypes =  AppDomain
            .CurrentDomain
            .GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .Where(type => typeof(A).IsAssignableFrom(type));
Run Code Online (Sandbox Code Playgroud)

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

var serializer = new DataContractSerializer(typeof(A), allTypes);
Run Code Online (Sandbox Code Playgroud)

就是这样 - 你将能够序列化和反序列化从A派生的任何类型(A可以是类或接口,如果接口,序列化器将元素写为派生自xs:anyType.