C# DataContract DataMember


Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML).

data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. 

 

Serializable標記大家都很熟悉,它是XmlSerializer的標記,在WCF中其實很少用這個標記,因為我們WCF用的是DataContractSerializer,對應的標記也是DataContract

Primitive類型默認是直接可被序列化的,自定義的類型要用DataContract序列化處理,WCF用DataContactSerializer。在WCF中一旦一個類被標記為DataContract,那么只有標記為DataMember的字段/屬性才會被序列化。

All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. 

 

DataContract也可以有繼承,但是child和parent都要有[DataContract]attribute:

[DataContract]
public class ConsoleData{
  [DataMember]
  public String Description{ get;set;}
}
[DataContract]
public class SomeData:ConsoleData{
  [DataMember]
  public int Volume{ get;set;}
}
但是在使用方面,這樣還不足夠,在用parent class作為參數的方法上,它無法識別child class object,所以要在parent DataContract上register child class:
[DataContract]
[KnownType(typeof(SomeData)]
public class ConsoleData{
[DataMember]
public String Description{ get;set;}
}
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM