VS.net在您创建WCF项目时创建模板.
它为iService1.cs文件添加了一个类:
// 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; }
}
}
Run Code Online (Sandbox Code Playgroud)
由于WCF服务可以返回任何用户定义的类,为什么要使用DataContract和CompositeType类?
我可以返回类似的东西:
[OperationContract]
MyUserCollection GetUsers();
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
Guy*_*uck 52
DataContract只是一种可以在服务边界两侧理解的类型的正式定义.
如果在示例中返回"MyUserCollection"对象,则服务的使用者将需要引用服务/系统的内部,这违反了明确边界的SOA原则.通过使用DataContract,您将以松散耦合的方式发布返回类型的结构.
Wag*_*ira 26
另一个有趣的事情是,如果您使用DataContract修饰代码,您可以对客户端可以看到的内容进行大量控制,并且必须将其发送回您的服务.例如:
[DataContract]
public class SampleClass
{
[DataMember(IsRequired=true)]
public int MyRequiredProperty { get; set; }
[DataMember]
public int MyOptionalProperty { get; set; }
public int MyInternalProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,您定义了在接收数据时,您必须具有MyRequiredProperty,并且您可以拥有或不拥有MyOptionalProperty.此外,客户端永远不会看到MyInternalProperty(例如,这可能是一些内部有助于您的逻辑的属性,但您不希望它在客户端级别公开).
Asi*_*taq 11
还有另一个重要用途,您可以更改类和属性的名称.在序列化和反序列化过程中,它是一个方便的功能.
[DataContract(Name="EmployeeName")]
public class Person
{
[DataMember(Name="FullName")]
public string Name { get; set; }
[DataMember(Name="HomeAddress")]
public string Address { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46001 次 |
| 最近记录: |