WCF datacontract vs class serialize

自闭症网瘾萝莉.ら 提交于 2020-01-02 02:31:07

问题


I understand that we can have more controls on a class if we use datacontract, however, consider the following 2 cases

[DataContract]
public class Customer
{
    [DataMember]
    public string CustomerName {get; set;}

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

and

public class Customer
{
    public string CustomerName {get; set;}
    public int Age{get; set;}
}

They both get serialized correctly on .net client. And personally I do not use second example. Can anybody point me the differences in the 2 classes? I meant to send all public properties in both classes.


回答1:


The second version is the POCO (plain old CLR object) version of your data contract and can be used with WCF since 3.5 sp1.

I would not recommend using it though as it gives you very little control on the serialization (namespace attributes...) and it couples your service entities with your business entities (which can be same with POCO)




回答2:


Anyway here is a better story from "Programming WCF services, 3rd Edition"

While using the Serializable attribute is workable, it is not ideal for service-oriented interaction between clients and services. Rather than denoting all members in a type as serializable and therefore part of the data schema for that type, it would be preferable to have an opt-in approach, where only members the contract developer wants to explicitly include in the data contract are included. The Serializable attribute forces the data type to be serializable in order to be used as a parameter in a contract operation, and it does not offer clean separation between the ability to use the type as a WCF operation parameter (the “serviceness” aspect of the type) and the ability to serialize it. The attribute offers no support for aliasing type names or members, or for mapping a new type to a predefined data contract. The attribute operates directly on member fields and completely bypasses any logical properties used to access those fields. It would be better to allow those properties to add their values when accessing the fields. Finally, there is no direct support for versioning, because the formatter supposedly captures all versioning information. Consequently, it is difficult to deal with versioning over time.



来源:https://stackoverflow.com/questions/4722136/wcf-datacontract-vs-class-serialize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!