DataContract序列化抽象类

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

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

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

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

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

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

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

获取实现给定抽象类或接口的所有已加载程序集中的所有类型(参考: 通过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派生的任何类型(如果接口,串行器将元素写为派生自xs:anyType,则可以是类或接口。