WCF的客戶端和服務端之所以能順利的傳輸某一類型的數據,其實不在於接收方的接收類型和發送方的發送類型一致,而實際是兩個類型所代表的DataContract是等價的。
所謂等價性是說DataContract的命名空間和名稱,及其數據字段的名稱,類別也是一致的。
通常DataContract的等價性是通過DataContractAttriubte和DataMemberAttribute的Name屬性來定義的,默認情況下Name屬性的值就是類(結構體)的名字和屬性的名字。因此如下定義效果是一樣的:
[c#] [DataContract]
class Contact { ... }
[DataContract(Name = "Contact")]
class Contact { ... }
[DataContract]
class Contact { ... }
[DataContract(Name = "Contact")]
class Contact { ... }同樣的,如下字段的定義效果也是一樣的:
[c#] view plaincopyprint?[DataMember]
public string Name;
[DataMember(Name = "Name")]
public string Name;
[DataMember]
public string Name;
[DataMember(Name = "Name")]
public string Name;因此,通過DataContractAttribute和DataMemberAttribute的Name字段可以實現不同的數據類型可以表示等價的DataContract,如:
[c#] [DataContract]
class Contact
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
}
[DataContract(Name = "Contact")]
class Person
{
[DataMember(Name = "FirstName")]
public string Name;
[DataMember(Name = "LastName")]
public string Surname;
}
[DataContract]
class Contact
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
}
[DataContract(Name = "Contact")]
class Person
{
[DataMember(Name = "FirstName")]
public string Name;
[DataMember(Name = "LastName")]
public string Surname;
}但是DataMemberAttribute還有一個屬性是Order,如下定義的兩個類則不是等價的。
[c#] [DataContract]
class Contact
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
}
[DataContract(Name = "Contact")]
class Person
{
[DataMember(Name = "FirstName", Order = 2)]
public string Name;
[DataMember(Name = "LastName", Order = 1)]
public string Surname;
}
[DataContract]
class Contact
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
}
[DataContract(Name = "Contact")]
class Person
{
[DataMember(Name = "FirstName", Order = 2)]
public string Name;
[DataMember(Name = "LastName", Order = 1)]
public string Surname;
}Order屬性決定了DataContract序列化和反序列化的順序,默認情況下,序列化和反序列化都是自上往下的,如果有繼承關系,也是按先基類後子類的順序。但是有一點需要注意就是,如果使用DataMember的Name屬性重新命名DataContract的字段時,可能會打亂默認的序列化順序。如下定義也不是等價的:
[c#] [DataContract]
class Contact
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
[DataMember]
public int Age;
}
[DataContract(Name = "Contact")]
class Person
{
[DataMember(Name = "FirstName")]
public string Name;
[DataMember(Name = "LastName")]
public string Surname;
[DataMember]
public int Age;
}
[DataContract]
class Contact
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
[DataMember]
public int Age;
}
[DataContract(Name = "Contact")]
class Person
{
[DataMember(Name = "FirstName")]
public string Name;
[DataMember(Name = "LastName")]
public string Surname;
[DataMember]
public int Age;
}Person類的序列化順序其實是Age, FirstName, LastName,因此需要顯示的添加Order屬性,如果類中的Order屬性是相等的,那麼就會按照自頂向下的順序序列化和反序列化。