XmlSerialize: 序列化是將對象轉換成易於傳輸的形式的過程。例如,可以序列化對象,並使用 HTTP 通過 Internet 在用戶端和伺服器之間進行傳輸。另一方面,還原序列化在流中重新構建對象。
XML 序列化只將對象的公用欄位和屬性值序列化為 XML 流。XML 序列化不包括類型資訊。例如,如果 Library 命名空間中存在 Book 對象,則不能保證將它還原序列化為同一類型的對象。
注意:
XML 序列化不能轉換方法、索引器、私人欄位或唯讀屬性(唯讀集合除外)。要序列化對象的所有公用和私人欄位和屬性,請使用 BinaryFormatter 而不要使用 XML 序列化。
SoapFormaterr:
以 SOAP 格式將對象或整個連線物件的圖形序列化和還原序列化。
BinaryFormatter:
以二進位格式將對象或整個連線物件圖形序列化和還原序列化。
委託可以通過 BinaryFormatter,SoapFormatter序列化,但是不能通過xmlSerialize序列化。
using System;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Xml.Serialization;
class Program
{
delegate void foo(string formatter);
static void Main(string[] args)
{
foo TestHandler = new foo(Test);
BinaryFormatter bFormatter = new BinaryFormatter();
SoapFormatter sFormatter =new SoapFormatter();
try
{
XmlSerializer xFormatter = new XmlSerializer(typeof(foo));
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
TestHandler("None");
string filePath = AppDomain.CurrentDomain.BaseDirectory;
string fileName="soap.xml";
string fullPath= Path.Combine(filePath, fileName);
string fileName2="binary.txt";
string fullPath2= Path.Combine(filePath, fileName2);
//string fileName3 = "xml.xml";
//string fullPath3 = Path.Combine(filePath, fileName3);
using (FileStream fs = new FileStream(fullPath, FileMode.Create))
{
sFormatter.Serialize(fs, TestHandler);
fs.Close();
}
using (FileStream fs2 = new FileStream(fullPath2, FileMode.Create))
{
bFormatter.Serialize(fs2, TestHandler);
fs2.Close();
}
using (FileStream fs = new FileStream(fullPath, FileMode.Open))
{
foo deserHandler = (foo)sFormatter.Deserialize(fs);
deserHandler("Soap");
fs.Close();
}
using (FileStream fs = new FileStream(fullPath2, FileMode.Open))
{
foo deserHandler = (foo)bFormatter.Deserialize(fs);
deserHandler("Binarry");
fs.Close();
}
Console.ReadLine();
}
static void Test(string formatter)
{
Console.WriteLine(" Formatter:{2} Test invoked. Call Time:{0} ticks:{1}",DateTime.Now.ToString(),DateTime.Now.Ticks.ToString(),formatter);
}
}
運行結果: