前一篇讲了系列化有三种方法,分别是XML,SOAP,二进制.
XML的命名空间为:using System.Xml.Serialization;
SOAP的命名空间为:using System.Runtime.Serialization.Formatters.Soap;(必须添加 System.Runtime.Serialization.Formatters.Soap的引用)
,二进制的命名空间:using System.Runtime.Serialization.Formatters.Binary;
今天我们就一起来学习系列化的具体方法.
首先看一段代码:
.net Remoting(2)序列化实例  // create a file stream to write the file
.net Remoting(2)序列化实例
        FileStream fileStream = new FileStream(@"C:/DoSum.xml", FileMode.Create);
.net Remoting(2)序列化实例        sObj 
= this.BuildSumObj();
.net Remoting(2)序列化实例
.net Remoting(2)序列化实例        
// use the CLR binary formatter
.net Remoting(2)序列化实例
        System.Xml.Serialization.XmlSerializer
.net Remoting(2)序列化实例            formatter 
= new XmlSerializer(typeof(SumOf));
.net Remoting(2)序列化实例        
// serialize to disk
.net Remoting(2)序列化实例
        formatter.Serialize(fileStream, sObj);
.net Remoting(2)序列化实例        fileStream.Close();
首先使用FileStream创建了个xml文件(添加using System.IO;),BuildSumObj()方法是给sObj加入0-9的数.代码如下:

.net Remoting(2)序列化实例 private SumOf BuildSumObj()
    }
SumOf是一个序列化的类,代码如下:
.net Remoting(2)序列化实例 [Serializable]
.net Remoting(2)序列化实例    
public class SumOf
生成的结果如下:
.net Remoting(2)序列化实例<?xml version="1.0"?>
.net Remoting(2)序列化实例
<SumOf xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
.net Remoting(2)序列化实例  
<Members>
.net Remoting(2)序列化实例    
<decimal>0</decimal>
.net Remoting(2)序列化实例    
<decimal>1</decimal>
.net Remoting(2)序列化实例    
<decimal>2</decimal>
.net Remoting(2)序列化实例    
<decimal>3</decimal>
.net Remoting(2)序列化实例    
<decimal>4</decimal>
.net Remoting(2)序列化实例    
<decimal>5</decimal>
.net Remoting(2)序列化实例    
<decimal>6</decimal>
.net Remoting(2)序列化实例    
<decimal>7</decimal>
.net Remoting(2)序列化实例    
<decimal>8</decimal>
.net Remoting(2)序列化实例    
<decimal>9</decimal>
.net Remoting(2)序列化实例  
</Members>
.net Remoting(2)序列化实例  
<Sum>45</Sum>
.net Remoting(2)序列化实例  
<Avg>4.5</Avg>
.net Remoting(2)序列化实例
</SumOf>

这个只是XML,其它的都雷同,在这里就不多说了.
在此感谢MSDN邵志东老师!
完整代码下载

相关文章:

  • 2022-12-23
  • 2022-02-22
  • 2022-03-05
  • 2021-06-24
  • 2022-01-02
  • 2021-12-23
  • 2021-04-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-27
  • 2021-06-25
  • 2021-10-27
  • 2022-02-07
  • 2021-12-08
相关资源
相似解决方案