DatacontractAttribute的使用规则
2024-08-28 23:12:11
关于DatacontractAttribute的使用规则和说明,
DatacontractAttribute是序列化类的另一种方法,和XmlMemberAttribute(也就是XmlElementAttribute)使用比较像。它的命名空间是System.Runtime.Serialization。
不同点:
DatacontractAttribute,必须定义DataMember,否则不序列化该字段;XmlMemberAttribute,默认是XmlElement。
序列化方法不一样,DatacontractAttribute使用DataContractSerializer;另一个使用XmlSerializer。
代码如下,
定义DataContract类代码
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=)]
public Guid ID
{
get;
set;
} private DateTime _date;
[DataMember(Order=)]
public DateTime Date
{
get;
set;
} [DataMember(Order = )]
public string Customer
{
get;
set;
} [DataMember(Order = )]
public string ShipAddress
{
get;
set;
} [DataMember(Order = )]
public double TotalPrice
{
get;
set;
}
} public class Order2 : DataBase2
{
[DataMember(Order = )]
public string PaymentType
{
get;
set;
}
}
}
调用DataContract
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 = ,
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);
} }
}
最新文章
- Maven创建web项目:SpringMVC+Mybatis 【转】
- ARM&;Linux 下驱动开发第二节
- centos6.5安装flume
- 【BZOJ 1090】[SCOI2003]字符串折叠
- 如何使用 Apache ab 以及 OneAPM 进行压力测试?
- alter和alert的一些问题
- Android之adb
- apache开源项目--Lens
- js 保留小数位数
- 利用PHPExcel转Excel柱形图
- 解開32位元Win 7記憶體4GB限制
- 8个新鲜的PHP常用代码
- iOS App内存优化之 解决UIImagePickerController的图片对象占用RAM过高问题
- MFC:位图和图标的设置
- HihoCoder - 1038 01背包 动态规划
- APK安装成功后点击";打开";,按Home键,在桌面点击图标后应用重启
- Linux实战
- 20165215 MySort的实现
- BZOJ3772精神污染——可持久化线段树+出栈入栈序
- pycharm 4注册码