NetDataContractSerializer 類別

定義

將某個類型的執行個體序列化及還原序列化成使用所提供 .NET Framework 類型的 XML 資料流或文件。Serializes and deserializes an instance of a type into XML stream or document using the supplied .NET Framework types. 這個類別無法被繼承。This class cannot be inherited.

public ref class NetDataContractSerializer sealed : System::Runtime::Serialization::XmlObjectSerializer, System::Runtime::Serialization::IFormatter
public sealed class NetDataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer, System.Runtime.Serialization.IFormatter
type NetDataContractSerializer = class
    inherit XmlObjectSerializer
    interface IFormatter
Public NotInheritable Class NetDataContractSerializer
Inherits XmlObjectSerializer
Implements IFormatter
繼承
NetDataContractSerializer
實作

範例

下列範例程式碼會示範名為 Person 且已由 NetDataContractSerializer 序列化的型別。The following example code shows a type named Person that is serialized by the NetDataContractSerializer. DataContractAttribute 屬性會套用至類別,而 DataMemberAttribute 會套用至成員 (包括私用成員),以便指示 NetDataContractSerializer 哪些項目需要序列化。The DataContractAttribute attribute is applied to the class, and the DataMemberAttribute is applied to members (including a private member) to instruct the NetDataContractSerializer what to serialize.

// You must apply a DataContractAttribute or SerializableAttribute
// to a class to have it serialized by the NetDataContractSerializer.
[DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
class Person : IExtensibleDataObject
{
    [DataMember()]
    public string FirstName;
    [DataMember]
    public string LastName;
    [DataMember()]
    public int ID;

    public Person(string newfName, string newLName, int newID)
    {
        FirstName = newfName;
        LastName = newLName;
        ID = newID;
    }

    private ExtensionDataObject extensionData_Value;

    public ExtensionDataObject ExtensionData
    {
        get
        {
            return extensionData_Value;
        }
        set
        {
            extensionData_Value = value;
        }
    }
}

public sealed class Test
{
    private Test() { }

    public static void Main()
    {
        try
        {
            WriteObject("NetDataContractSerializerExample.xml");
            ReadObject("NetDataContractSerializerExample.xml");
        }

        catch (SerializationException serExc)
        {
            Console.WriteLine("Serialization Failed");
            Console.WriteLine(serExc.Message);
        }
        catch (Exception exc)
        {
            Console.WriteLine(
            "The serialization operation failed: {0} StackTrace: {1}",
            exc.Message, exc.StackTrace);
        }

        finally
        {
            Console.WriteLine("Press <Enter> to exit....");
            Console.ReadLine();
        }
    }

    public static void WriteObject(string fileName)
    {
        Console.WriteLine(
            "Creating a Person object and serializing it.");
        Person p1 = new Person("Zighetti", "Barbara", 101);
        FileStream fs = new FileStream(fileName, FileMode.Create);
        XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
        NetDataContractSerializer ser =
            new NetDataContractSerializer();
        ser.WriteObject(writer, p1);
        writer.Close();
    }

    public static void ReadObject(string fileName)
    {
        Console.WriteLine("Deserializing an instance of the object.");
        FileStream fs = new FileStream(fileName,
        FileMode.Open);
        XmlDictionaryReader reader =
            XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
        NetDataContractSerializer ser = new NetDataContractSerializer();

        // Deserialize the data and read it from the instance.
        Person deserializedPerson =
            (Person)ser.ReadObject(reader, true);
        fs.Close();
        Console.WriteLine(String.Format("{0} {1}, ID: {2}",
        deserializedPerson.FirstName, deserializedPerson.LastName,
        deserializedPerson.ID));
    }
}
' You must apply a DataContractAttribute or SerializableAttribute
' to a class to have it serialized by the NetDataContractSerializer.
<DataContract(Name := "Customer", [Namespace] := "http://www.contoso.com")>  _
Class Person
    Implements IExtensibleDataObject
    <DataMember()>  _
    Public FirstName As String
    <DataMember()>  _
    Public LastName As String
    <DataMember()>  _
    Public ID As Integer
    
    
    Public Sub New(ByVal newfName As String, ByVal newLName As String, _
       ByVal newID As Integer) 
        FirstName = newfName
        LastName = newLName
        ID = newID
    
    End Sub 
    
    Private extensionData_Value As ExtensionDataObject
    
    
    Public Property ExtensionData() As ExtensionDataObject _
     Implements IExtensibleDataObject.ExtensionData
        Get
            Return extensionData_Value
        End Get
        Set
            extensionData_Value = value
        End Set
    End Property
End Class 


NotInheritable Public Class Test

    Private Sub New() 
    
    End Sub
     
    Public Shared Sub Main() 
        Try
            WriteObject("NetDataContractSerializerExample.xml")
            ReadObject("NetDataContractSerializerExample.xml")
        
        Catch serExc As SerializationException
            Console.WriteLine("Serialization Failed")
            Console.WriteLine(serExc.Message)
        Catch exc As Exception
            Console.WriteLine("The serialization operation failed: {0} StackTrace: {1}", exc.Message, exc.StackTrace)
        
        Finally
            Console.WriteLine("Press <Enter> to exit....")
            Console.ReadLine()
        End Try
    
    End Sub 
    
    
    Public Shared Sub WriteObject(ByVal fileName As String) 
        Console.WriteLine("Creating a Person object and serializing it.")
        Dim p1 As New Person("Zighetti", "Barbara", 101)
        Dim fs As New FileStream(fileName, FileMode.Create)
        Dim writer As XmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(fs)
        Dim ser As New System.Runtime.Serialization.NetDataContractSerializer()

        ser.WriteObject(writer, p1)
        writer.Close()
    
    End Sub     

    Public Shared Sub ReadObject(ByVal fileName As String) 
        Console.WriteLine("Deserializing an instance of the object.")
        Dim fs As New FileStream(fileName, FileMode.Open)
        Dim reader As XmlDictionaryReader = _
           XmlDictionaryReader.CreateTextReader(fs, New XmlDictionaryReaderQuotas())
        Dim ser As New System.Runtime.Serialization.NetDataContractSerializer()
        
        ' Deserialize the data and read it from the instance.
        Dim deserializedPerson As Person = CType(ser.ReadObject(reader, True), Person)
        fs.Close()
        Console.WriteLine(String.Format("{0} {1}, ID: {2}", deserializedPerson.FirstName, deserializedPerson.LastName, deserializedPerson.ID))
    
    End Sub 
End Class 

備註

NetDataContractSerializerDataContractSerializer 有一項重要的差異:NetDataContractSerializer 在已序列化的 XML 中包含 CLR 型別資訊,而 DataContractSerializer 則否。The NetDataContractSerializer differs from the DataContractSerializer in one important way: the NetDataContractSerializer includes CLR type information in the serialized XML, whereas the DataContractSerializer does not. 因此,只有當序列化和還原序列化兩端共用相同的 CLR 型別時,才能使用 NetDataContractSerializerTherefore, the NetDataContractSerializer can be used only if both the serializing and deserializing ends share the same CLR types.

序列化程式可以將型別序列化至已套用 DataContractAttributeSerializableAttribute 屬性的型別。The serializer can serialize types to which either the DataContractAttribute or SerializableAttribute attribute has been applied. 它也會序列化實作 ISerializable 的型別。It also serializes types that implement ISerializable.

如需序列化的詳細資訊, 請參閱序列化和還原序列化For more information about serialization, see Serialization and Deserialization.

與 XElement 的不相容性Incompatibility with XElement

XElement 類別會用於寫入 XML。The XElement class is used to write XML. 然而,NetDataContractSerializer 無法序列化該型別的執行個體。However, the NetDataContractSerializer cannot serialize an instance of the type. 因此, 下列程式碼會失敗並出現例外狀況:NetDataContractSerializer 的頂層不支援「根類型」 system.xml.linq.xelement> ', 因為它是 IXmlSerializable IsAny = true , 而且必須寫入其所有內容, 包括根項目。」The following code, therefore, fails with the exception: "Root type 'System.Xml.Linq.XElement' is not supported at the top level by NetDataContractSerializer since it is IXmlSerializable with IsAny=true and must write all its contents including the root element."

FileStream fs = new FileStream("mystuff.xml", FileMode.Create, FileAccess.ReadWrite);
XElement myElement = new XElement("Parent", new XElement("child1", "form"),
    new XElement("child2", "base"),
    new XElement("child3", "formbase")
    );
NetDataContractSerializer dcs = new NetDataContractSerializer();
dcs.WriteObject(fs, myElement);
Dim fs As New FileStream("mystuff.xml", FileMode.Create, FileAccess.ReadWrite)
Dim myElement As New XElement("Parent", New XElement("child1", "form"), _
    New XElement("child2", "base"), _
    New XElement("child3", "formbase") _
    )
Dim ser As New System.Runtime.Serialization. _
  NetDataContractSerializer()
ser.WriteObject(fs, myElement)

然而,如果 XElement 是用來做為類別之欄位或屬性的型別,該欄位或屬性所包含的資料就會進行序列化。However, if an XElement is used as the type of a field or property of a class, the data contained by the field or property is serialized. 這是因為當做為類別的成員時,該資料並不是位於類別的最上層。This is because as a member of a class, the data is not the top level of the class.

建構函式

NetDataContractSerializer()

初始化 NetDataContractSerializer 類別的新執行個體。Initializes a new instance of the NetDataContractSerializer class.

NetDataContractSerializer(StreamingContext)

使用提供的資料流內容資料,初始化 NetDataContractSerializer 類別的新執行個體。Initializes a new instance of the NetDataContractSerializer class with the supplied streaming context data.

NetDataContractSerializer(StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)

使用提供的內容資料,初始化 NetDataContractSerializer 類別的新執行個體;此外,指定物件中要序列化的最大項目數,以及指定是否要略過額外資料的參數、組件載入方法和代理選取器。Initializes a new instance of the NetDataContractSerializer class with the supplied context data; in addition, specifies the maximum number of items in the object to be serialized, and parameters to specify whether extra data is ignored, the assembly loading method, and a surrogate selector.

NetDataContractSerializer(String, String)

使用提供的 XML 根項目和命名空間,初始化 NetDataContractSerializer 類別的新執行個體。Initializes a new instance of the NetDataContractSerializer class with the supplied XML root element and namespace.

NetDataContractSerializer(String, String, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)

使用提供的內容資料以及根名稱和命名空間,初始化 NetDataContractSerializer 類別的新執行個體;此外,指定物件中要序列化的最大項目數,以及指定是否要略過額外資料的參數、組件載入方法和代理選取器。Initializes a new instance of the NetDataContractSerializer class with the supplied context data and root name and namespace; in addition, specifies the maximum number of items in the object to be serialized, and parameters to specify whether extra data is ignored, the assembly loading method, and a surrogate selector.

NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString)

使用包含用於指定內容之根項目和命名空間的兩個 NetDataContractSerializer 型別參數,初始化 XmlDictionaryString 類別的新執行個體。Initializes a new instance of the NetDataContractSerializer class with two parameters of type XmlDictionaryString that contain the root element and namespace used to specify the content.

NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)

使用提供的內容資料以及根名稱和命名空間 (相同於 XmlDictionaryString 參數的處理方式),初始化 NetDataContractSerializer 類別的新執行個體;此外,指定物件中要序列化的最大項目數,以及指定是否要略過額外資料的參數、組件載入方法和代理選取器。Initializes a new instance of the NetDataContractSerializer class with the supplied context data, and root name and namespace (as XmlDictionaryString parameters); in addition, specifies the maximum number of items in the object to be serialized, and parameters to specify whether extra data found is ignored, assembly loading method, and a surrogate selector.

屬性

AssemblyFormat

取得值,這個值會指定用來尋找及載入組件的方法。Gets a value that specifies a method for locating and loading assemblies.

Binder

取得或設定會控制類別載入的物件。Gets or sets an object that controls class loading.

Context

取得或設定物件,該物件可傳遞對序列化或還原序列化期間有用的內容資料。Gets or sets the object that enables the passing of context data that is useful while serializing or deserializing.

IgnoreExtensionDataObject

取得值,這個值會指定是否略過物件延伸所提供的資料。Gets a value that specifies whether data supplied by an extension of the object is ignored.

MaxItemsInObjectGraph

取得允許物件中要序列化的最大項目數。Gets the maximum number of items allowed in the object to be serialized.

SurrogateSelector

取得或設定物件,該物件會協助選取用於序列化之代理時的格式器。Gets or sets an object that assists the formatter when selecting a surrogate for serialization.

方法

Deserialize(Stream)

將 XML 文件或資料流還原序列化成物件。Deserializes an XML document or stream into an object.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
IsStartObject(XmlDictionaryReader)

判斷 XmlDictionaryReader 是否置於可使用已指定讀取器而還原序列化的物件上。Determines whether the XmlDictionaryReader is positioned on an object that can be deserialized using the specified reader.

IsStartObject(XmlReader)

判斷 XmlReader 是否置於可使用已指定讀取器而還原序列化的物件上。Determines whether the XmlReader is positioned on an object that can be deserialized using the specified reader.

MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ReadObject(Stream)

使用 Stream 讀取 XML 資料流或文件,然後傳回已還原序列化的物件。Reads the XML stream or document with a Stream and returns the deserialized object.

(繼承來源 XmlObjectSerializer)
ReadObject(XmlDictionaryReader)

使用 XmlDictionaryReader 讀取 XML 文件或資料流,然後傳回已還原序列化的物件。Reads the XML document or stream with an XmlDictionaryReader and returns the deserialized object.

(繼承來源 XmlObjectSerializer)
ReadObject(XmlDictionaryReader, Boolean)

使用 XmlDictionaryReader 讀取 XML 資料流或文件,然後傳回已還原序列化的物件;同時檢查該物件資料是否符合用於建立序列化程式的名稱和命名空間。Reads the XML stream or document with an XmlDictionaryReader and returns the deserialized object; also checks whether the object data conforms to the name and namespace used to create the serializer.

ReadObject(XmlReader)

使用 XmlDictionaryReader 讀取 XML 資料流或文件,然後傳回已還原序列化的物件。Reads the XML stream or document with an XmlDictionaryReader and returns the deserialized object.

ReadObject(XmlReader, Boolean)

使用 XmlDictionaryReader 讀取 XML 資料流或文件,然後傳回已還原序列化的物件;同時檢查該物件資料是否符合用於建立序列化程式的名稱和命名空間。Reads the XML stream or document with an XmlDictionaryReader and returns the deserialized object; also checks whether the object data conforms to the name and namespace used to create the serializer.

Serialize(Stream, Object)

使用指定的寫入器序列化指定的物件圖形。Serializes the specified object graph using the specified writer.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)
WriteEndObject(XmlDictionaryWriter)

使用 XmlDictionaryWriter 寫入結尾 XML 項目。Writes the closing XML element using an XmlDictionaryWriter.

WriteEndObject(XmlWriter)

使用 XmlWriter 寫入結尾 XML 項目。Writes the closing XML element using an XmlWriter.

WriteObject(Stream, Object)

使用指定的 Stream,將物件的完整內容 (開始、內容和結束) 寫入至 XML 文件或資料流。Writes the complete content (start, content, and end) of the object to the XML document or stream with the specified Stream.

(繼承來源 XmlObjectSerializer)
WriteObject(XmlDictionaryWriter, Object)

使用指定的 XmlDictionaryWriter,將物件的完整內容 (開始、內容和結束) 寫入至 XML 文件或資料流。Writes the complete content (start, content, and end) of the object to the XML document or stream with the specified XmlDictionaryWriter.

(繼承來源 XmlObjectSerializer)
WriteObject(XmlWriter, Object)

使用指定的 XmlWriter,將物件的完整內容 (開始、內容和結束) 寫入至 XML 文件或資料流。Writes the complete content (start, content, and end) of the object to the XML document or stream with the specified XmlWriter.

WriteObjectContent(XmlDictionaryWriter, Object)

使用 XmlDictionaryWriter 寫入 XML 內容。Writes the XML content using an XmlDictionaryWriter.

WriteObjectContent(XmlWriter, Object)

使用 XmlWriter 寫入 XML 內容。Writes the XML content using an XmlWriter.

WriteStartObject(XmlDictionaryWriter, Object)

使用 XmlDictionaryWriter 寫入開頭 XML 項目。Writes the opening XML element using an XmlDictionaryWriter.

WriteStartObject(XmlWriter, Object)

使用 XmlWriter 寫入開頭 XML 項目。Writes the opening XML element using an XmlWriter.

適用於

另請參閱