閱讀965 返回首頁    go 技術社區[雲棲]


對象序列化反序列化例子

using System; using System.IO; using System.Xml.Serialization; [Serializable] public class Model { public string Name{get;set;} public string Possword{get;set;} public override string ToString() { return "Name:"+ Name+"possword:"+Possword; } } class App { static void Main() { Model model=new Model(); model.Name="old Man"; model.Possword="123456"; Console.WriteLine("序列化:"); string str=Serialize(model); System.Console.WriteLine(str); Console.WriteLine("反序列化:"); Model newModel=(Model)Deserialize((typeof(Model)),str); Console.WriteLine(newModel.ToString()); } #region 對象序列化 /// <summary> /// 序列化對象 /// </summary> /// <typeparam name="T">對象類型</typeparam> /// <param name="t">對象</param> /// <returns></returns> public static string Serialize<T>(T t) { using (StringWriter sw = new StringWriter()) { XmlSerializer xz = new XmlSerializer(t.GetType()); xz.Serialize(sw, t); return sw.ToString(); } } /// <summary> /// 反序列化為對象 /// </summary> /// <param name="type">對象類型</param> /// <param name="s">對象序列化後的Xml字符串</param> /// <returns></returns> public static object Deserialize(Type type, string s) { using (StringReader sr = new StringReader(s)) { XmlSerializer xz = new XmlSerializer(type); return xz.Deserialize(sr); } } #endregion }

最後更新:2017-04-02 06:51:42

  上一篇:go Intent跳轉
  下一篇:go MySQL Innodb日誌機製深入分析