BinaryFormatter和SoapFormatter在对于类型处理方面有两个明显的区别:
以下是一个演示二者区别的示例:
[Serializable]
public class Person
{
public string Name { get; set; }
}
public static void Main()
{
var person = new Person { Name = "Alice" };
var binaryFormatter = new BinaryFormatter();
var binaryStream = new MemoryStream();
binaryFormatter.Serialize(binaryStream, person);
binaryStream.Seek(0, SeekOrigin.Begin);
var binaryPerson = (Person)binaryFormatter.Deserialize(binaryStream);
var soapFormatter = new SoapFormatter();
var soapStream = new MemoryStream();
soapFormatter.Serialize(soapStream, person);
soapStream.Seek(0, SeekOrigin.Begin);
var soapPerson = (Person)soapFormatter.Deserialize(soapStream);
}
在上面的示例中,我们创建了一个名为Person的可序列化对象,并使用BinaryFormatter和SoapFormatter分别对其进行序列化和反序列化操作。在使用BinaryFormatter时,我们需要使用明确的类型信息对其进行序列化,而在使用SoapFormatter时则无需明确类型信息。
需要注意的是,SoapFormatter已经被弃用,因为它存在安全漏洞,推荐使用其他序列化方案,如JSON或MessagePack。