WCF - 是否在 .NET 3.5 SP1 中使用 [DataContract]? [英] WCF - To Use [DataContract] or not with .NET 3.5 SP1?

查看:22
本文介绍了WCF - 是否在 .NET 3.5 SP1 中使用 [DataContract]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WCF .NET 3.5 SP1,并且读到不必用 [DataMember]、[DataConract] 和/或 [Serializable] 之类的东西来装饰他们的实体/集合?最好的方法是什么?大家都遇到了什么?

I am working with WCF .NET 3.5 SP1 and have read that one does NOT have to decorate their Entities/Collections with such things as [DataMember], [DataConract], and/or [Serializable]? What is the best way to go? What have you all encountered?

我使用的是 3.5 SP1.

I am on 3.5 SP1.

推荐答案

参见 使用数据契约.

您创建的新复杂类型必须为他们定义数据合同可序列化.默认情况下,DataContractSerializer 推断数据合同和序列化所有公开可见类型.所有公共读/写类型的属性和字段是连载.您可以选择退出会员从序列化使用IgnoreDataMemberAttribute.你可以还明确地创建了一个数据契约通过使用 DataContractAttributeDataMemberAttribute 属性.这个通常是通过应用DataContractAttribute 属性到类型.该属性可以应用于类、结构和枚举.DataMemberAttribute 属性必须然后应用于每个成员数据契约类型来表明它是一个数据成员,也就是说,它应该被序列化.想要查询更多的信息,请参阅可序列化类型.

New complex types that you create must have a data contract defined for them to be serializable. By default, the DataContractSerializer infers the data contract and serializes all publicly visible types. All public read/write properties and fields of the type are serialized. You can opt out members from serialization by using the IgnoreDataMemberAttribute. You can also explicitly create a data contract by using DataContractAttribute and DataMemberAttribute attributes. This is normally done by applying the DataContractAttribute attribute to the type. This attribute can be applied to classes, structures, and enumerations. The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized. For more information, see Serializable Types.

就像@Terry 所说的那样,主动声明要公开的属性可能会更好.通过这种方式,您可以在未来证明您的代码不会在基类将来添加公共属性时无意中暴露字段.

Like @Terry said, it's probably better to proactively declare which properties you want to expose. This way you could future proof your code from unintentionally exposing fields when the base class adds a public property in the future.

这篇关于WCF - 是否在 .NET 3.5 SP1 中使用 [DataContract]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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