DataContract序列化抽象类 [英] DataContract Serialize abstract class

查看:127
本文介绍了DataContract序列化抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口IServiceInfo和一个抽象类ServiceInfo。从ServiceInfo继承了几个类,例如CoreServiceInfo,ModuleServiceInfo等。有一个名为RootService的服务协定,该协定返回IServiceInfo。

I have an interface IServiceInfo and an abstract class ServiceInfo. There are several classes inherited from ServiceInfo, like CoreServiceInfo, ModuleServiceInfo etc. There is a service contract named RootService which returns IServiceInfo.

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

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

I am having problem serializing. I can use ServiceKnownType to identify base class, and KnownType to identify child class.

问题是我不知道所有ServiceInfo子级,因为应用程序可以具有带有不同子级的插件

Problem is I do not know all the ServiceInfo child, since application can have plugins with different child inherited from ServiceInfo, so I cannot tell serializer to have all the child in serialized XML.

我可以忽略抽象类,但是它包含某些通用实现,因此我需要保留它。作为一种变通方法,我可以让另一个类说 sampleServiceInfo,然后将所有信息类转换为sampleServiceInfo,然后将其从Service方法返回,然后将KnownType定义为ServiceInfo类。

I can ignore abstract class, but it contains certain common implementation so I need to keep it. As a work around I can have another class say "sampleServiceInfo" and convert all the info classes to sampleServiceInfo and return it from Service method, and define KnownType to ServiceInfo class.

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

但这听起来不是实现它的好方法。请提出建议。我需要编写自定义序列化程序吗?

But that does not sound pretty way to do it. Please suggest. Do I need to write custom serializer? Is there any way to serialize base only and ignoring the child when both has same members?

推荐答案

获取所有已加载的所有类型,是否有任何方法只能序列化base并忽略子级?实现给定抽象类或接口的程序集(参考:通过反射实现接口

Get all the types in all loaded assemblies that implement given abstract class or interface(ref:Implementations of interface through Reflection)

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

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

Then create serializer passing allTypes as known types parameter, as below

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

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

that's it - you will be able to serialize and deserialize any type that derives from A (A could be class or interface, if interface, serializer writes elements as deriving from xs:anyType.

这篇关于DataContract序列化抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆