.NET Framework 類庫 |
BinaryFormatter 類
Serializes and deserializes an object, or an entire graph of connected objects, in binary format.
有關此類型所有成員的清單,請參閱 BinaryFormatter 成員。
System.Object
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
[Visual Basic]
NotInheritable Public Class BinaryFormatter
Implements IRemotingFormatter, IFormatter
[C#]
public sealed class BinaryFormatter : IRemotingFormatter,
IFormatter
[C++]
public __gc __sealed class BinaryFormatter : public
IRemotingFormatter, IFormatter
[JScript]
public class BinaryFormatter implements IRemotingFormatter,
IFormatter
線程安全
此類型的所有公共靜态(Visual Basic 中為 Shared)成員是線程安全的。但不保證任何執行個體成員是線程安全的。
備注
The SoapFormatter and BinaryFormatter classes implement the IRemotingFormatter interface to support remote procedure calls (RPCs), and the IFormatter interface (inherited by the IRemotingFormatter) to support serialization of a graph of objects. The SoapFormatter class also supports RPCs with ISoapMessage objects, without using the IRemotingFormatter functionality.
During RPCs, the IRemotingFormatter interface allows the specification of two separate object graphs: the graph of objects to serialize, and an additional graph containing an array of header objects that convey information about the remote function call (for example, transaction ID or a method signature).
RPCs that use the BinaryFormatter separate into two distinct parts: method calls, which are sent to the server with the remote object containing the method called, and method responses, which are sent from the server to the client with the status and response information from the called method.
During serialization of a method call the first object of the object graph must support the IMethodCallMessage interface. To deserialize a method call, use the Deserialize method with the HeaderHandler parameter. The remoting infrastructure uses the HeaderHandler delegate to produce an object that supports the ISerializable interface. When the BinaryFormatter invokes the HeaderHandler delegate, it returns the URI of the remote object with the method that is being called. The first object in the graph returned supports the IMethodCallMessage interface.
The serialization procedure for a method response is identical to that of a method call, except the first object of the object graph must support the IMethodReturnMessage interface. To deserialize a method response, use the DeserializeMethodResponse method. To save time, details about the caller object are not sent to the remote object during the method call. These details are instead obtained from the original method call, which is passed to the DeserializeMethodResponse method in the IMethodCallMessage parameter. The first object in the graph returned by the DeserializeMethodResponse method supports the IMethodReturnMessage interface.
示例
[Visual Basic]
Imports System.IO
Imports System.Collections
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Module App
Sub Main()
Serialize()
Deserialize()
End Sub
Sub Serialize()
' Create a hashtable of values that will eventually be serialized.
Dim addresses As New Hashtable
addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052")
addresses.Add("Fred", "987 Pine Road, Phila., PA 19116")
addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301")
' To serialize the hashtable (and its key/value pairs),
' you must first open a stream for writing.
' In this case, use a file stream.
Dim fs As New FileStream("DataFile.dat", FileMode.Create)
' Construct a BinaryFormatter and use it to serialize the data to the stream.
Dim formatter As New BinaryFormatter
Try
formatter.Serialize(fs, addresses)
Catch e As SerializationException
Console.WriteLine("Failed to serialize. Reason: " & e.Message)
Throw
Finally
fs.Close()
End Try
End Sub
Sub Deserialize()
' Declare the hashtable reference.
Dim addresses As Hashtable = Nothing
' Open the file containing the data that you want to deserialize.
Dim fs As New FileStream("DataFile.dat", FileMode.Open)
Try
Dim formatter As New BinaryFormatter
' Deserialize the hashtable from the file and
' assign the reference to the local variable.
addresses = DirectCast(formatter.Deserialize(fs), Hashtable)
Catch e As SerializationException
Console.WriteLine("Failed to deserialize. Reason: " & e.Message)
Throw
Finally
fs.Close()
End Try
' To prove that the table deserialized correctly,
' display the key/value pairs.
Dim de As DictionaryEntry
For Each de In addresses
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value)
Next
End Sub
End Module
[C#]
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public class App
{
[STAThread]
static void Main()
{
Serialize();
Deserialize();
}
static void Serialize()
{
// Create a hashtable of values that will eventually be serialized.
Hashtable addresses = new Hashtable();
addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");
// To serialize the hashtable and its key/value pairs,
// you must first open a stream for writing.
// In this case, use a file stream.
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, addresses);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
static void Deserialize()
{
// Declare the hashtable reference.
Hashtable addresses = null;
// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
addresses = (Hashtable) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
// To prove that the table deserialized correctly,
// display the key/value pairs.
foreach (DictionaryEntry de in addresses)
{
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
}
}
}
[C++]
#using <mscorlib.dll>
using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Runtime::Serialization;
__gc class App
{
public:
static void Serialize()
{
// Create a hashtable of values that will eventually be serialized.
Hashtable* addresses = new Hashtable();
addresses->Add(S"Jeff", S"123 Main Street, Redmond, WA 98052");
addresses->Add(S"Fred", S"987 Pine Road, Phila., PA 19116");
addresses->Add(S"Mary", S"PO Box 112233, Palo Alto, CA 94301");
// To serialize the hashtable (and its keys/values),
// you must first open a stream for writing.
// In this case we will use a file stream.
FileStream* fs = new FileStream(S"DataFile.dat", FileMode::Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter* formatter = new BinaryFormatter();
try
{
formatter->Serialize(fs, addresses);
}
catch (SerializationException* e)
{
Console::WriteLine(S"Failed to serialize. Reason: {0}", e->Message);
throw;
}
__finally
{
fs->Close();
}
}
static void Deserialize()
{
// Declare the hashtable reference.
Hashtable* addresses = 0;
// Open the file containing the data that we want to deserialize.
FileStream* fs = new FileStream(S"DataFile.dat", FileMode::Open);
try
{
BinaryFormatter* formatter = new BinaryFormatter();
// Deserialize the hashtable from the file and
// assign the reference to our local variable.
addresses = dynamic_cast<Hashtable*>(formatter->Deserialize(fs));
}
catch (SerializationException* e)
{
Console::WriteLine(S"Failed to deserialize. Reason: {0}", e->Message);
throw;
}
__finally
{
fs->Close();
}
// To prove that the table deserialized correctly, display the keys/values.
IEnumerator* myEnum = addresses->GetEnumerator();
while (myEnum->MoveNext())
{
DictionaryEntry* de = __try_cast<DictionaryEntry*>(myEnum->Current);
Console::WriteLine(S" {0} lives at {1}.", de->Key, de->Value);
}
}
};
[STAThread]
int main()
{
App::Serialize();
App::Deserialize();
return 0;
}
[JScript] 沒有可用于 JScript 的示例。若要檢視 Visual Basic、C# 或 C++ 示例,請單擊頁左上角的“語言篩選器”按鈕

。
要求
命名空間: System.Runtime.Serialization.Formatters.Binary
平台: Windows 98, Windows NT 4.0, Windows ME, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 系列
程式集: Mscorlib (在 Mscorlib.dll 中)
請參見
BinaryFormatter 成員 | System.Runtime.Serialization.Formatters.Binary 命名空間
*************************************************** 1 C#關于串行的問題1---BinaryFormatter
有時候需要将C#中某一個結構很複雜的類的對象存儲起來,或者通過網路傳輸到遠端的用戶端程式中去, 這時候用檔案方式或者資料庫方式存儲或者傳送就比較麻煩了,這個時候,最好的辦法就是使用串行和解串(Serialization & Deserialization). .NET中串行有三種,BinaryFormatter, SoapFormatter和XmlSerializer. 其中BinaryFormattter最簡單,它是直接用二進制方式把對象(Object)進行串行或反串,他的優點是速度快,可以串行private或者protected的member, 在不同版本的。NET中都相容,可以看作是。NET自己的本命方法,當然缺點也就随之而來了,離開了。NET它就活不了,是以不能在其他平台或跨網路上進行。 運用BinaryFormatter的步驟也相當直覺和簡單。 1。在你需要串行的類裡,用[Serializable]聲明這個類是可以串行的,當然有些不想被串行的元素,可以用[NonSerialized]屬性來屏蔽。如果有些元素是新版本中添加的,可以用屬性[FieldOption]來增加相容性。 2。生成一個流Stream, 裡面包含你想存儲資料的檔案或者網絡流. 3。建立一個BinaryFormatter類的Object. 4。然後就可以直接用方法Serialize/Deserialize來串行或者反串了。(注意這兩個方法不是static的,是以你非得建立一個對象不可)。 舉例如下:
串行: FileStream fs = new FileStream("SerializedDate.data", FileMode.Create);
BinaryFormatter bf = New BinaryFormatter();
// Here is the object that you want to be serialized
MyClass mc = new MyClass();
// here put something in mc.
bf.Serialize(fs, mc);
fs.Close(); 反串行: FileStream fs = new FileStream("SerializedDate.data", FileMode.Open);
BinaryFormatter bf = New BinaryFormatter();
MyClass mc = new MyClass(); // used to restore the object
mc = (MyClass)bf.Deserialize(fs);
fs.Close(); 就這麼簡單。 2 C#關于串行的問題2---SoapFormatter
如果知道了BinaryFormatter的串行和反串行方法,那麼SoapFormatter的方法也就知道了, 因為它們是完全類同的。 SoapFormatter應用非常廣泛,因為它是在XML文本基礎上運用SOAP的技術來實行串行和反串的,是以可以跨平台和跨網路使用,而且另外一點,它存儲的XML格式便于閱讀和操作。 比起BinaryFormatter, SoapFormatter的串行還支援幾個屬性attribute: SoapAttribute, 就是把元素存儲成XML裡的attribute,
SoapElement,
SoapEnum,
SoapIgnore,屏蔽此元素。
SoapInclude, 其他的所有一切用法,就跟上面所講的BinayFormattter一樣的,隻不過是把BinaryFormatter換成SoapFormatter而已。 BinaryFormatter在System.Runtime.Serialization.Formatters.Binary域名裡。
類似的,SoapFormatter在System.Runtime.Serialization.Formatters.Soap裡。