日期:2014-05-20 浏览次数:20789 次
using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Text.RegularExpressions; using System.Xml.Serialization; namespace Demo { public class MyObject { public string Name { get; set; } public string Sex { get; set; } [XmlIgnore] public Type DataType { get; set; } [XmlElement("DataType")] public string DataTypeName { get { return DataType.ToString(); } set { DataType = Type.GetType(value); } } } internal class Program { private static void Main(string[] args) { MyObject obj = new MyObject() {Name = "jim", Sex = "Male", DataType = typeof (int)}; XmlSerializer serializer = new XmlSerializer(typeof (MyObject)); MemoryStream ms = new MemoryStream(); serializer.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(ms); string xml = sr.ReadToEnd(); Console.WriteLine(xml); ms.Seek(0, SeekOrigin.Begin); MyObject obj2 = serializer.Deserialize(ms) as MyObject; Console.WriteLine(obj.DataType == obj2.DataType); Console.WriteLine(obj.Name == obj2.Name); Console.WriteLine(obj.Sex == obj2.Sex); Console.ReadLine(); } } }