DataContract序列化抽象类

时间:2010-12-21 02:49:30

标签: c# wcf serialization abstract

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

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

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

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

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

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

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

1 个答案:

答案 0 :(得分:7)

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