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);
}
}
运行结果: