【问题标题】:DataContract Serialize abstract classDataContract 序列化抽象类
【发布时间】:2010-12-21 02:49:29
【问题描述】:

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

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

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

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

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

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

但这听起来不太好。请建议。我需要编写自定义序列化程序吗?有没有办法只序列化 base 并在两者具有相同成员时忽略孩子?

【问题讨论】:

  • 如果您自己不了解派生类,您如何期望 .NET 了解它?
  • 这是边界,应用程序包含可插拔服务

标签: c# wcf serialization abstract


【解决方案1】:

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

【讨论】:

  • 感谢 mho,所以最后我需要编写自定义序列化程序。我期待一些类级别的属性忽略序列化,或者一些不错的模式,或者类似的东西。太好了,无论如何谢谢。
  • @hungryMind 如果回答了这个问题,您最好通过检查投票旋转器下方的标记来标记它。
猜你喜欢
  • 2010-10-12
  • 1970-01-01
  • 2017-11-06
  • 2019-05-22
  • 2016-01-04
  • 2012-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多