關於DatacontractAttribute的使用規則和說明,ide
DatacontractAttribute是序列化類的另外一種方法,和XmlMemberAttribute(也就是XmlElementAttribute)使用比較像。它的命名空間是System.Runtime.Serialization。ui
不一樣點:spa
DatacontractAttribute,必須定義DataMember,不然不序列化該字段;XmlMemberAttribute,默認是XmlElement。code
序列化方法不同,DatacontractAttribute使用DataContractSerializer;另外一個使用XmlSerializer。xml
代碼以下,blog
定義DataContract類代碼ip
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.Data; using System.ServiceModel; using System.Xml; using System.Runtime.Serialization; namespace Artech.XmlSerializerDemos { [DataContract] public class DataBase2 { [DataMember(Order=1)] public Guid ID { get; set; } private DateTime _date; [DataMember(Order=2)] public DateTime Date { get; set; } [DataMember(Order = 3)] public string Customer { get; set; } [DataMember(Order = 4)] public string ShipAddress { get; set; } [DataMember(Order = 5)] public double TotalPrice { get; set; } } public class Order2 : DataBase2 { [DataMember(Order = 1)] public string PaymentType { get; set; } } }
調用DataContractget
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Runtime.Serialization; using System.Diagnostics; namespace Artech.XmlSerializerDemos { class Program { static void Main(string[] args) { #region DataContract Order2 order = new Order2() { ID = Guid.NewGuid(), Date = DateTime.Today, Customer = "Foo", ShipAddress = "airport address", TotalPrice = 8888, PaymentType = "credit card" }; Serialize<Order2>(order, @"E:\Order.xml"); #endregion #region xml Attribute //Order order = new Order() //{ // ID = Guid.NewGuid(), // Date = DateTime.Today, // Customer = "Foo", // ShipAddress = "airport address" //}; //Serialize<Order>(order, @"E:\Order.xml"); #endregion } static void Serialize<T>(T instance, string fileName) { #region xml Attribute //using (XmlWriter writer = new XmlTextWriter(fileName, Encoding.UTF8)) //{ // XmlSerializer serializer = new XmlSerializer(typeof(T)); // serializer.Serialize(writer, instance); //} #endregion #region xml datacontract using (XmlWriter writer = new XmlTextWriter(fileName, Encoding.UTF8)) { DataContractSerializer serializer = new DataContractSerializer(typeof(T)); serializer.WriteObject(writer, instance); } #endregion Process.Start(fileName); } } }