WCF 中的 DataContract 有什么意义? [英] What's the point of a DataContract in WCF?
问题描述
VS.net 在您创建 WCF 项目时创建模板.
VS.net creates a template when you create a WCF project.
它在 iService1.cs 文件中添加了一个类:
It adds a class to the iService1.cs file:
// Use a data contract as illustrated in the sample below to
// add composite types to service operations.
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
既然 WCF 服务可以返回任何用户定义的类,为什么要使用 DataContract 和 CompositeType 类?
Since a WCF service can return any user defined class, why use a DataContract and CompositeType class?
我可以返回如下内容:
[OperationContract]
MyUserCollection GetUsers();
我错过了什么?
推荐答案
DataContract 只是对服务边界两边都可以理解的类型的正式定义.
The DataContract is just a formal definition of a type that can be understood on both sides of the service boundary.
如果您在示例中返回MyUserCollection"对象,则您的服务使用者将需要引用您的服务/系统的内部结构,这违反了 SOA 明确边界原则.通过使用 DataContract,您可以以松散耦合的方式发布返回类型的结构.
If you return, as in your example, a "MyUserCollection" object, the consumers of your service will need to reference the innards of your service/system, which is a violation of the SOA tenet of explicit boundaries. By using a DataContract, you are publishing the structure of your return types in a loosely-coupled way.
这篇关于WCF 中的 DataContract 有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!