C# 实现复杂对象的序列化与反序列化

      (注:本篇文章是本人根据msdn,各位同行的心得再加上自己对序列化的一些想法汇集而成,如有不当,还请指教)
     
    序列化是将对象转换为容易传输的格式的过程。例如,可以序列化一个对象,然后使用 HTTP 通过 Internet 在客户端和服务器之间传输该对象。反之,反序列化根据流重新构造对象。这里主要介绍两种序列的方法:一是XML 序列化,二是Binary序列化。

         1.   XML序列

            XML 序列化仅将对象的公共字段和属性值序列化为 XML 流。XML 序列化不包括类型信息。例如,如果 Library 命名空间中有一个 Book 对象,将不能保证它会被反序列化为同一类型的对象。XML 序列化不转换方法、索引器、私有字段或只读属性(只读集合除外)。要序列化对象的所有字段和属性(公共的和私有的),请使用 BinaryFormatter,而不要使用 XML 序列化.XML 序列化中最主要的类是 XmlSerializer 类,它的最重要的方法是 Serialize 和 Deserialize 方法。我们可以利用它提供这两个方法实现对象的序列与反序列.下面我提供我自己编写的code,主要是用xmlserialize来实现对象的序列与反序列,代码如下:
   
         首先,声明两个用来序列的对象,一个用户设置对象和一个图层参数对象,用户设置对象包括了用户信息和一个图层列表:

 1/// <summary>
 2    /// 图层参数
 3    /// </summary>

 4    [Serializable]
 5    public class LayerPara
 6    {
 7        public int ID;
 8        public string MC;               // 中文名称
 9        public string Layer;            // 数据集名称
10        public short GBCode;            // 分类码
11        public short GeoType;           // 图层对应的几何类型, 11表示点图层,12表示线图层
12        public int MinScale;            // 显示的最小比例尺
13    }

14    [Serializable]
15    public class UserSetting
16    {
17        public string strUserName = "kandy";
18        public string strUserPwd = "123456789";
19        public List<LayerPara> userLayerParas;
20    }

21

     然后,声明一个进行序列与反序列的类,其中WriteDataToFile实现将文件写如本地指定的路径,ReadDataFormFile方法实现将文件从磁盘中读取:

class Serialize
    
{
        
        
public List<UserSetting> m_LayerParamsList;
        
public UserSetting userSetting;
        
public Serialize()
        
{
            
this.ResetLayersInfo();
            
this.WriteDataToFile(userSetting);
        }


        
private void ResetLayersInfo()
        
{
            m_LayerParamsList 
= new List<UserSetting>();

            userSetting 
= new UserSetting();
            userSetting.userLayerParas 
= new List<LayerPara>();
            

            LayerPara layerPara 
= new LayerPara();
            layerPara.ID 
= 100;
            layerPara.MC 
= "管点";
            layerPara.Layer 
= "gd";
            layerPara.GBCode 
= 4;
            layerPara.GeoType 
= 5;
            layerPara.MinScale 
= 100;

            userSetting.userLayerParas.Add(layerPara);
            
               layerPara = new LayerPara();
            layerPara.ID 
= 200;
            layerPara.MC 
= "管线";
            layerPara.Layer 
= "gx";
            layerPara.GBCode 
= 5;
            layerPara.GeoType 
= 6;
            layerPara.MinScale 
= 100;

            userSetting.userLayerParas.Add(layerPara);
           
        }


        
private void WriteDataToFile(UserSetting tempUserSetting)
        
{
            
if (tempUserSetting != null)
            
{
                
try
                
{
                    
string strSaveToPath = AppDomain.CurrentDomain.BaseDirectory;
                    strSaveToPath 
= strSaveToPath + "UserLayerSetting.xml";
                    Stream stream 
= new FileStream(strSaveToPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    XmlSerializer xmlFormatter 
= new XmlSerializer(typeof(UserSetting));
                    xmlFormatter.Serialize(stream, tempUserSetting);
                    stream.Close();

                    Console.WriteLine(
" serialize is finished!");
                }

                
catch (InvalidOperationException e)
                
{
                    Console.WriteLine(e.Message);
                }

            }

        }


        
public UserSetting ReadDataFormFile()
        
{
            UserSetting setting 
= new UserSetting();
            
string strSaveToPath = AppDomain.CurrentDomain.BaseDirectory;
            strSaveToPath 
= strSaveToPath + "UserLayerSetting.xml";

            
bool isExist = this.IsExsitFileInAppPath(strSaveToPath);
            
if (isExist)
            
{
                Stream stream 
= new FileStream(strSaveToPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer formatter 
= new XmlSerializer(typeof(UserSetting));
                
try
                
{
                    setting 
= (UserSetting)formatter.Deserialize(stream);
                    Console.WriteLine(setting.strUserName);
                    Console.WriteLine(setting.strUserPwd);
                    
foreach(LayerPara lp in setting.userLayerParas)
                    
{
                        Console.WriteLine(lp.ID.ToString());
                        Console.WriteLine(lp.MC);
                        Console.WriteLine(lp.Layer);
                        Console.WriteLine(lp.GBCode.ToString());
                        Console.WriteLine(lp.GeoType.ToString());
                        Console.WriteLine(lp.MinScale);
                        Console.WriteLine(
"\n");
                    }

                }

                
catch (SerializationException e)
                
{
                    Console.WriteLine(e.Message);
                }

            }

            
else
                Console.WriteLine(
"File is not Exist!");

            
return setting;
        }


        
private bool IsExsitFileInAppPath(string strTempPath)
        
{
            
bool bExsit = false;
            bExsit 
= File.Exists(strTempPath);
            
return bExsit;
        }

        
    }

现在我们就可以在Main()方法中进行调用了,下面是一个进行测试的类,包含了主程序的Main()方法:

public class Testing
    
{
        
public static void Main()
        
{
            Console.WriteLine(
"Serialize is beginning");

            Serialize serialize 
= new Serialize();
            serialize.ReadDataFormFile();
            Console.WriteLine(
"Read have finished!");
            Console.Read();
            
        }

    }

   2.Binary序列
      这里主要谈的是BinaryFormatter,它位于System.Runtime.Serialization.Formatters.Binary名字空间下,以二进制格式将对象或整个连接对象图形序列化和反序列化。个人认为BinaryFormatter比第一种方法更好用,它同样也有Serialize和DeSerialize方法,具体代码我就贴序列与反序列的代码了,其原理与过程都大致相同,下面是序列与反序列的代码:

private void SaveLayerToAppPath(List<LayerPara> tempLayerParas)
        
{
            
if (tempLayerParas != null)
            
{
                
string strSaveToPath=AppDomain.CurrentDomain.BaseDirectory;
                strSaveToPath
=strSaveToPath+"layer.dat";
                Stream stream 
= new FileStream(strSaveToPath, FileMode.Create, FileAccess.Write, FileShare.None);
                IFormatter formatter 
= new BinaryFormatter();
                formatter.Serialize(stream, tempLayerParas);
                stream.Close();

                Console.WriteLine(
" serialize is success!");
            }

        }


        
public List<LayerPara> ReadDataFormFile()
        
{
            List
<LayerPara> tempLayerPara = new List<LayerPara>();

            
string strSaveToPath = AppDomain.CurrentDomain.BaseDirectory;
            strSaveToPath 
= strSaveToPath + "layer.dat";

            
bool isExist = this.IsExsitFileInAppPath(strSaveToPath);
            
if (isExist)
            
{
                Stream stream 
= new FileStream(strSaveToPath, FileMode.Open, FileAccess.Read, FileShare.None);
                BinaryFormatter formatter 
= new BinaryFormatter();

                
try
                
{
                    tempLayerPara 
= (List<LayerPara>)formatter.Deserialize(stream);
                    
foreach (LayerPara lp in tempLayerPara)
                    
{
                        Console.WriteLine(lp.ID.ToString());
                        Console.WriteLine(lp.MC);
                        Console.WriteLine(lp.Layer);
                        Console.WriteLine(lp.GBCode.ToString());
                        Console.WriteLine(lp.GeoType.ToString());
                        Console.WriteLine(lp.MinScale);
                    }

                }

                
catch (SerializationException e)
                
{
                    Console.WriteLine(e.Message);
                }

            }

            
else
                Console.WriteLine(
"File is not Exist!");

            
return tempLayerPara;
        }

   总结:主要是根据的实际项目需要了,看你适合哪种方法.

原文地址:https://www.cnblogs.com/hanchan/p/832257.html