.NET Framework 类库 BinaryFormatter 类

.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里。  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值