DataContract Serialize 抽象类 [英] DataContract Serialize abstract class
问题描述
我有一个接口 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 子项,因为应用程序可以有继承自 ServiceInfo 的不同子项的插件,所以我不能告诉序列化程序将所有子项都放在序列化的 XML 中.
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?
推荐答案
获取实现给定抽象类或接口的所有加载程序集中的所有类型(ref:通过反射实现接口)
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 Serialize 抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!