如何使用WCF序列化派生类型作为其基本类型 [英] How to serialize a derived type as its base type with WCF

查看:83
本文介绍了如何使用WCF序列化派生类型作为其基本类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个公共图书馆,里面有一些物件.然后,我有一个服务项目,该项目引用了公共库并从公共库中的对象创建了一些派生类型.

I have a common library with some objects in it. Then I have a service project that references the common library and creates some derived types from objects in the common library.

我希望我的服务将派生类型序列化为公共库中定义的基本类型.

I want my service to serialize the derived types as their base types defined in the common library.

我不能在公共库中的对象上使用KnownTypes,因为我不希望公共库引用服务程序集.

I cannot use KnownTypes on the objects in the common library because I don't want the common library referencing the service assemblies.

那我怎样才能wcf序列化派生类型作为它们的基本类型?

So how can I have wcf serialize the derived types as their base types?

我希望我可以做类似的事情...

I wish I could do something like...

[DataContract(SerializeAsType = typeof(BaseType))] 公共类DerivedType:BaseType { }

[DataContract(SerializeAsType = typeof(BaseType))] public class DerivedType : BaseType { }

像这样可能吗?

推荐答案

您是否正在使用.NET 4.0?您可以在以下情况下使用DataContractResolver:

Are you using .NET 4.0? You can use the DataContractResolver for this if you are:

http://msdn.microsoft.com/zh-CN/library/system.runtime.serialization.datacontractresolver.aspx

这基本上也是Entity Framework 4.0为其代理类型的DataContractResolver所做的事情.

This is also basically what Entity Framework 4.0 does for its DataContractResolver for proxy types.

这里是一个示例: http ://blogs.msdn.com/b/youssefm/archive/2009/06/05/introducing-a-new-datacontractserializer-feature-the-datacontractresolver.aspx

(请参阅链接中的DeserializeAsBaseResolver).

(see DeserializeAsBaseResolver in the link).

如果您不使用.NET 4.0,那么我认为您的下一个最佳选择是DataContractSurrogate: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.idatacontractsurrogate.aspx . ...因此您可以手动控制序列化,但这会变得混乱.

If you're not using .NET 4.0, I think your next best option is a DataContractSurrogate: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.idatacontractsurrogate.aspx. ...so you can control the serialization by hand, but this can get messy.

两者都传递到DataContractSerializer的构造函数中,并且可以通过DataContractSerializerOperationBehavior为WCF配置:

Both are passed into the constructor of your DataContractSerializer and can be configured for WCF via the DataContractSerializerOperationBehavior: http://msdn.microsoft.com/en-us/library/system.servicemodel.description.datacontractserializeroperationbehavior.aspx.

这篇关于如何使用WCF序列化派生类型作为其基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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