序列化和DataContract(不是对?) [英] Serializable and DataContract (not versus?)

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

问题描述

我读了一些代码在我的新项目,并发现了前开发商用序列化和DataContract在一起。

I am reading some code in my new project and found out the ex-developer was using Serializable and DataContract together.

[Serializable]

[DataContract(Namespace="Some.Name.Space", IsReference = true)]

我假设时,有一个DataContract属性WCF会忽略Serializable接口。这是一个正确的假设?如果不是,那么在同一时间使用两种好处?

I assume WCF will ignore Serializable when there is a DataContract attribute. Is this a correct assumption? If not, what are the benefits to use both at the same time?

推荐答案

[Serializable接口] 是,如果<$ C $忽略C> [DataContract] 存在。这可能是例如有用创建一个类型将有WCF一个序列投影,而另一个投影为.NET远程处理(如果它一起使用WCF遗留原因)。

Yes, [Serializable] is ignored if [DataContract] is present. This may be useful to e.g. create a type that will have one serialization projection for WCF, and another projection for .NET Remoting (if it is used alongside WCF for legacy reasons).

更新:我刚跑进自己的代码,其中两个 [DataContract] [Serializable接口] 情况是必要的。假设你有一堆自动生成的属性的一类(如公众诠释美孚{获取;集;} ),您要使用的两个在ASP.NET的ViewState,并在ASP.NET Web API JSON端点(使用无论是Newtonsoft JSON序列化或DataContractSerializer的)。对于ViewState的工作,你需要的类是 [Serializable接口] 。然而,这打破JSON序列化,造成JSON像 {_ k_BackingField123:456} 而不是 {富:456} ,因为 [Serializable接口] 模型自动生成的属性支持字段被序列化,而不是属性本身。不过,如果你的 [DataContract] 添加到类型(以及 [数据成员] 其属性),无论是ViewState中和JSON场景很好地工作。

UPDATE: I just ran into a situation in my own code where both [DataContract] and [Serializable] were necessary. Suppose you have a class with a bunch of auto-generated properties (e.g. public int Foo {get; set;}) that you want to use both in ASP.NET ViewState and in an ASP.NET Web API JSON endpoint (which uses either the Newtonsoft JSON serializer or the DataContractSerializer). For ViewState to work, you need the class to be [Serializable]. However, this breaks JSON serialization, causing JSON like {"_k_BackingField123":456} instead of {"Foo":456}, because in the [Serializable] model the auto-generated property backing fields get serialized instead of the properties themselves. However, if you also add [DataContract] to the type (and [DataMember] to its properties), both the ViewState and the JSON scenarios work perfectly.

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

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