.NET Framework 类库 |
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 命名空间
有时候需要将C#中某一个结构很复杂的类的对象存储起来,或者通过网路传输到远程的客户端程序中去, 这时候用文件方式或者数据库方式存储或者传送就比较麻烦了,这个时候,最好的办法就是使用串行和解串(Serialization & Deserialization).
串行:
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();
BinaryFormatter bf = New BinaryFormatter();
MyClass mc = new MyClass(); // used to restore the object
mc = (MyClass)bf.Deserialize(fs);
fs.Close();
如果知道了BinaryFormatter的串行和反串行方法,那么SoapFormatter的方法也就知道了, 因为它们是完全类同的。
SoapElement,
SoapEnum,
SoapIgnore,屏蔽此元素。
SoapInclude,
类似的,SoapFormatter在System.Runtime.Serialization.Formatters.Soap里。