C# 串行化与反串行化--使用SoapFormatter进行串行化

来源:互联网 发布:java 两种状态的按钮 编辑:程序博客网 时间:2024/06/05 10:46

2、使用SoapFormatter进行串行化

串行化的文件是xml格式,只能串行化由基础类型组成的对象,不支持泛型,继承等关系的对象。

[csharp] view plain copy
  1. [Serializable()]  
  2.     public class SoapSerialize  
  3.     {  
  4.         private int id;  
  5.         public int ID  
  6.         {  
  7.             get { return id; }  
  8.             set { id = value; }  
  9.         }  
  10.   
  11.         private string name;  
  12.         public string Name  
  13.         {  
  14.             get { return name; }  
  15.             set { name = value; }  
  16.         }  
  17.   
  18.         private SexType sex;  
  19.         public SexType Sex  
  20.         {  
  21.             get { return sex; }  
  22.             set { sex = value; }  
  23.         }  
  24.   
  25.         private string[] list;  
  26.         public string[] List  
  27.         {  
  28.             get { return list; }  
  29.             set { list = value; }  
  30.         }  
  31.         //private List<string> listStr;  
  32.         //public List<string> ListStr  
  33.         //{  
  34.         //    get { return listStr; }  
  35.         //    set { listStr = value; }  
  36.         //}  
  37.   
  38.         //private ListBuffer buffer = new ListBuffer();  
  39.         //public ListBuffer Buffer  
  40.         //{  
  41.         //    get { return buffer; }  
  42.         //    set { buffer = value; }  
  43.         //}  
  44.     }  
  45.   
  46.     public sealed class ConfigurationManagerSoapSerialize  
  47.     {  
  48.         private static string path = System.Windows.Forms.Application.StartupPath + "\\SoapSerialize.xml";  
  49.   
  50.         public static SoapSerialize Get()  
  51.         {  
  52.             if (!File.Exists(path))  
  53.                 return null;  
  54.   
  55.             SoapFormatter b = new SoapFormatter();  
  56.             using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))  
  57.             {  
  58.                 return (SoapSerialize)b.Deserialize(fs);  
  59.             }  
  60.         }  
  61.   
  62.         public static void Set(SoapSerialize hr)  
  63.         {  
  64.             SoapFormatter b = new SoapFormatter();  
  65.             using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))  
  66.             {  
  67.                 b.Serialize(fs, hr);  
  68.             }  
  69.         }  
  70.     }  

备注:

soap序列化连泛型都不支持,所以没有进行更多的研究,能用就用,不能用就换一个方式。

原创粉丝点击