码迷,mamicode.com
首页 > 其他好文 > 详细

When to use DataContract and DataMember attributes?

时间:2015-07-21 12:10:18      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

When to use DataContract and DataMember attributes?

 I  am very confused about the DataContract attribute in WCF. As per my knowledge it is used for serialization user defined type like classes. I write a one class which is expose at client side.

[DataContract]
public class Contact
{
    [DataMember]
    public int Roll { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Address { get; set; }

    [DataMember]
    public int Age { get; set; }
}

It is working properly but when I remove DataContract at class level as well as DataMember it is also work properly. I can‘t understand that if it is working properly so why there is a need of DataContract? Can any one tell me what is the actual use of DataContract?

My service contract looks like this

[ServiceContract]    
public interface IRestServiceImpl
{
    [OperationContract]        
    Contact XmlData(string id);      
}

 

 

 

解答:

Since a lot of programmers were overwhelmed with the [DataContract] and [DataMember]attributes, with .NET 3.5 SP1, Microsoft made the data contract serializer handle all classes - even without any of those attributes - much like the old XML serializer.

So as of .NET 3.5 SP1, you don‘t have to add data contract or data member attributes anymore - if you don‘t then the data contract serializer will serialize all public properties on your class, just like the XML serializer would.

HOWEVER: by not adding those attributes, you lose a lot of useful capabilities:

  • without [DataContract], you cannot define an XML namespace for your data to live in
  • without [DataMember], you cannot serialize non-public properties or fields
  • without [DataMember], you cannot define an order of serialization (Order=) and the DCS will serialize all properties alphabetically
  • without [DataMember], you cannot define a different name for your property (Name=)
  • without [DataMember], you cannot define things like IsRequired= or other useful attributes
  • without [DataMember], you cannot leave out certain public properties - all public properties will be serialized by the DCS

So for a "quick‘n‘dirty" solution, leaving away the [DataContract] and [DataMember] attributes will work - but it‘s still a good idea to have them on your data classes - just to be more explicit about what you‘re doing, and to give yourself access to all those additional features that you don‘t get without them...

When to use DataContract and DataMember attributes?

标签:

原文地址:http://www.cnblogs.com/chucklu/p/4663930.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!