DataContractSerializer DataContractSerializer DataContractSerializer DataContractSerializer Class

定義

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

public ref class DataContractSerializer sealed : System::Runtime::Serialization::XmlObjectSerializer
public sealed class DataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer
type DataContractSerializer = class
    inherit XmlObjectSerializer
Public NotInheritable Class DataContractSerializer
Inherits XmlObjectSerializer
繼承
DataContractSerializerDataContractSerializerDataContractSerializerDataContractSerializer

範例

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

namespace DataContractSerializerExample
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Xml;

    // You must apply a DataContractAttribute or SerializableAttribute
    // to a class to have it serialized by the DataContractSerializer.
    [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("DataContractSerializerExample.xml");
                ReadObject("DataContractSerializerExample.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 writer = new FileStream(fileName, FileMode.Create);
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Person));
            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());
            DataContractSerializer ser = new DataContractSerializer(typeof(Person));

            // Deserialize the data and read it from the instance.
            Person deserializedPerson =
                (Person)ser.ReadObject(reader, true);
            reader.Close();
            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 DataContractSerializer.
<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("DataContractSerializerExample.xml")
            ReadObject("DataContractSerializerExample.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 writer As New FileStream(fileName, FileMode.Create)
        Dim ser As New DataContractSerializer(GetType(Person))
        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 DataContractSerializer(GetType(Person))
        
        ' Deserialize the data and read it from the instance.
        Dim deserializedPerson As Person = CType(ser.ReadObject(reader, True), Person)
        reader.Close()
        fs.Close()
        Console.WriteLine(String.Format("{0} {1}, ID: {2}", deserializedPerson.FirstName, deserializedPerson.LastName, deserializedPerson.ID))
    End Sub 
End Class 

備註

使用 DataContractSerializer 類別,即可將某個型別的執行個體序列化及還原序列化成 XML 資料流或文件。Use the DataContractSerializer class to serialize and deserialize instances of a type into an XML stream or document. 例如,您可以使用包含基本資料的屬性 (例如姓名和地址) 來建立名為 Person 的型別。For example, you can create a type named Person with properties that contain essential data, such as a name and address. 接著,您可以建立及操作 Person 類別的執行個體,並將所有的屬性值寫入 XML 文件中以供日後擷取,或寫入 XML 資料流中以供立即傳輸。You can then create and manipulate an instance of the Person class and write all of its property values in an XML document for later retrieval, or in an XML stream for immediate transport. 最重要的是,DataContractSerializer用來序列化和還原序列化 Windows Communication Foundation (WCF) 訊息中傳送的資料。Most important, the DataContractSerializer is used to serialize and deserialize data sent in Windows Communication Foundation (WCF) messages. DataContractAttribute 屬性套用至類別,並將 DataMemberAttribute 屬性套用至類別成員,即可指定已序列化的屬性和欄位。Apply the DataContractAttribute attribute to classes, and the DataMemberAttribute attribute to class members to specify properties and fields that are serialized.

如需可序列化的類型,請參閱Types Supported by the Data Contract SerializerFor a list of types that can be serialized, see Types Supported by the Data Contract Serializer.

如果要使用 DataContractSerializer,請先建立類別的執行個體,以及適合用於寫入或讀取此格式的物件;例如,XmlDictionaryWriter 的執行個體。To use the DataContractSerializer, first create an instance of a class and an object appropriate to writing or reading the format; for example, an instance of the XmlDictionaryWriter. 接著,呼叫 WriteObject 方法以保留資料。Then call the WriteObject method to persist the data. 如果要擷取資料,請建立適合用於讀取此資料格式的物件 (例如適合 XML 文件的 XmlDictionaryReader),接著呼叫 ReadObject 方法。To retrieve data, create an object appropriate to reading the data format (such as an XmlDictionaryReader for an XML document) and call the ReadObject method.

如需使用詳細資訊DataContractSerializer,請參閱 < 序列化和還原序列化For more information about using the DataContractSerializer, see Serialization and Deserialization.

您可以設定使用資料合約序列化程式的型別 <dataContractSerializer> 用戶端應用程式組態檔中的項目。You can set the type of a data contract serializer using the <dataContractSerializer> element in a client application configuration file.

準備類別以進行序列化或還原序列化Preparing Classes for Serialization or Deserialization

DataContractSerializer 會組合 DataContractAttributeDataMemberAttribute 類別一起使用。The DataContractSerializer is used in combination with the DataContractAttribute and DataMemberAttribute classes. 如果要準備類別以進行序列化,請將 DataContractAttribute 套用至此類別。To prepare a class for serialization, apply the DataContractAttribute to the class. 對於每個會傳回您要序列化之資料的類別成員,請套用 DataMemberAttributeFor each member of the class that returns data that you want to serialize, apply the DataMemberAttribute. 您可以序列化欄位和屬性,不論其存取範圍為何:private、protected、internal、protected internal 或 public。You can serialize fields and properties, regardless of accessibility: private, protected, internal, protected internal, or public.

例如,您的結構描述指定含有 Customer 屬性的 ID,但是您的現有應用程式是使用名為 Person 且具有 Name 屬性的型別。For example, your schema specifies a Customer with an ID property, but you already have an existing application that uses a type named Person with a Name property. 如果要建立符合該合約的型別,請先將 DataContractAttribute 套用至類別。To create a type that conforms to the contract, first apply the DataContractAttribute to the class. 然後將 DataMemberAttribute 套用至要序列化的每個欄位或屬性。Then apply the DataMemberAttribute to every field or property that you want to serialize.

注意

您可以將 DataMemberAttribute 同時套用至 Private 和 Public 成員。You can apply the DataMemberAttribute to both private and public members.

XML 的最終格式並不要求一定是文字。The final format of the XML need not be text. 相反地,DataContractSerializer 會將資料寫成為 XML infoset,這樣您便可以將資料寫成任何可由 XmlReaderXmlWriter 辨識的格式。Instead, the DataContractSerializer writes the data as an XML infoset, which allows you to write the data to any format recognized by the XmlReader and XmlWriter. 建議您使用 XmlDictionaryReaderXmlDictionaryWriter 類別來讀取和寫入,因為這兩種類別已針對使用 DataContractSerializer 完成最佳化。It is recommended that you use the XmlDictionaryReader and XmlDictionaryWriter classes to read and write, because both are optimized to work with the DataContractSerializer.

如果您要建立具有欄位或屬性必須填入序列化之前的類別,或還原序列化,就會發生,使用回呼屬性中所述版本相容序列化回呼If you are creating a class that has fields or properties that must be populated before the serialization or deserialization occurs, use callback attributes, as described in Version-Tolerant Serialization Callbacks.

新增至已知型別集合Adding to the Collection of Known Types

當序列化或還原序列化物件時,其型別必須是 DataContractSerializer「已知」的型別。When serializing or deserializing an object, it is required that the type is "known" to the DataContractSerializer. 一開始會先建立會實作 IEnumerable<T> (例如 List<T>) 之類別的執行個體,並將已知型別新增至集合。Begin by creating an instance of a class that implements IEnumerable<T> (such as List<T>) and adding the known types to the collection. 接下來,建立使用接受 DataContractSerializer 之其中一個多載的 IEnumerable<T> 執行個體 (例如,DataContractSerializer(Type, IEnumerable<Type>)Then create an instance of the DataContractSerializer using one of the overloads that takes the IEnumerable<T> (for example, DataContractSerializer(Type, IEnumerable<Type>).

注意

不同於其他基本類型,DateTimeOffset結構不是已知的型別,根據預設,因此它必須以手動方式新增至已知型別的清單 (請參閱 < Data Contract Known Types)。Unlike other primitive types, the DateTimeOffset structure is not a known type by default, so it must be manually added to the list of known types (see Data Contract Known Types).

正向相容性Forward Compatibility

DataContractSerializer 知道資料合約已設計為與合約的未來版本相容。The DataContractSerializer understands data contracts that have been designed to be compatible with future versions of the contract. 這些型別會實作 IExtensibleDataObject 介面。Such types implement the IExtensibleDataObject interface. 此介面的特色是會傳回 ExtensionData 物件的 ExtensionDataObject 屬性。The interface features the ExtensionData property that returns an ExtensionDataObject object. 如需詳細資訊,請參閱向前相容資料合約For more information, see Forward-Compatible Data Contracts.

在部分信任下執行Running under Partial Trust

在還原序列化期間產生目標物件時,DataContractSerializer 不會呼叫目標物件的建構函式。When instantiating the target object during deserialization, the DataContractSerializer does not call the constructor of the target object. 如果您撰寫 [DataContract] 型別可從部分信任存取 (也就是說,它屬於 public,而且組件中具有AllowPartiallyTrustedCallers套用的屬性) 和執行一些與安全性相關的動作,您必須知道,不會呼叫建構函式。If you author a [DataContract] type that is accessible from partial trust (that is, it is public and in an assembly that has the AllowPartiallyTrustedCallers attribute applied) and that performs some security-related actions, you must be aware that the constructor is not called. 特別值得一提的是,下列技巧將無法運作:In particular, the following techniques do not work:

  • 如果您嘗試透過將建構函式設為 internal 或 private,或是將 LinkDemand 新增至建構函式等方式來限制部分信任存取,上述這些方式都無法在部分信任環境中的還原序列化期間發揮作用。If you try to restrict partial trust access by making the constructor internal or private, or by adding a LinkDemand to the constructor -- neither of these have any effect during deserialization under partial trust.

  • 如果您撰寫的類別程式碼會假定該建構函式已經執行,則此類別可能會處於易遭利用的無效 internal 狀態。If you code the class that assumes the constructor has run, the class may get into an invalid internal state that is exploitable.

建構函式

DataContractSerializer(Type) DataContractSerializer(Type) DataContractSerializer(Type) DataContractSerializer(Type)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type.

DataContractSerializer(Type, DataContractSerializerSettings) DataContractSerializer(Type, DataContractSerializerSettings) DataContractSerializer(Type, DataContractSerializerSettings) DataContractSerializer(Type, DataContractSerializerSettings)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別及設定的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type and settings.

DataContractSerializer(Type, IEnumerable<Type>) DataContractSerializer(Type, IEnumerable<Type>) DataContractSerializer(Type, IEnumerable<Type>) DataContractSerializer(Type, IEnumerable<Type>)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件,以及可能存在物件圖形中的已知型別集合。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type, and a collection of known types that may be present in the object graph.

DataContractSerializer(Type, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate) DataContractSerializer(Type, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate) DataContractSerializer(Type, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate) DataContractSerializer(Type, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type. 這個方法也會指定可能存在物件圖形中之已知型別的清單,要序列化之圖形項目的最大數,要略過非預期資料的參數,是否要使用非標準的 XML 建構來保存圖形中的物件參考資料,以及自訂序列化的代理。This method also specifies a list of known types that may be present in the object graph, the maximum number of graph items to serialize, parameters to ignore unexpected data, whether to use non-standard XML constructs to preserve object reference data in the graph, and a surrogate for custom serialization.

DataContractSerializer(Type, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver) DataContractSerializer(Type, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver) DataContractSerializer(Type, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver) DataContractSerializer(Type, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type. 這個方法也會指定可能存在物件圖形中之已知型別的清單、要序列化之圖形項目的最大數、要略過非預期資料的參數、是否要使用非標準的 XML 建構來保存圖形中的物件參考資料、自訂序列化的代理,以及在執行階段對應 xsi:type 宣告的替代方式。This method also specifies a list of known types that may be present in the object graph, the maximum number of graph items to serialize, parameters to ignore unexpected data, whether to use non-standard XML constructs to preserve object reference data in the graph, a surrogate for custom serialization, and an alternative for mapping xsi:type declarations at run time.

DataContractSerializer(Type, String, String) DataContractSerializer(Type, String, String) DataContractSerializer(Type, String, String) DataContractSerializer(Type, String, String)

初始化 DataContractSerializer 類別的新執行個體,以便序列化或還原序列化已指定型別的物件 (該型別會使用提供的 XML 根項目和命名空間)。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type using the supplied XML root element and namespace.

DataContractSerializer(Type, String, String, IEnumerable<Type>) DataContractSerializer(Type, String, String, IEnumerable<Type>) DataContractSerializer(Type, String, String, IEnumerable<Type>) DataContractSerializer(Type, String, String, IEnumerable<Type>)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type. 這個方法也會透過兩個字串參數來指定根 XML 項目和命名空間,以及可能存在於物件圖形內之已知型別的清單。This method also specifies the root XML element and namespace in two string parameters as well as a list of known types that may be present in the object graph.

DataContractSerializer(Type, String, String, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate) DataContractSerializer(Type, String, String, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate) DataContractSerializer(Type, String, String, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate) DataContractSerializer(Type, String, String, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type. 這個方法也會指定可能存在物件圖形中之已知型別的清單、要序列化之圖形項目的最大數、要略過非預期資料的參數、是否要使用非標準的 XML 建構來保存圖形中的物件參考資料、自訂序列化的代理,以及含有內容的 XML 項目和命名空間。This method also specifies a list of known types that may be present in the object graph, the maximum number of graph items to serialize, parameters to ignore unexpected data, whether to use non-standard XML constructs to preserve object reference data in the graph, a surrogate for custom serialization, and the XML element and namespace that contain the content.

DataContractSerializer(Type, String, String, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver) DataContractSerializer(Type, String, String, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver) DataContractSerializer(Type, String, String, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver) DataContractSerializer(Type, String, String, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type. 這個方法也會指定可能存在物件圖形中之已知型別的清單、要序列化之圖形項目的最大數、要略過非預期資料的參數、是否要使用非標準的 XML 建構來保存圖形中的物件參考資料、自訂序列化的代理、XML 項目和包含內容的命名空間,以及在執行階段對應 xsi:type 宣告的替代方式。This method also specifies a list of known types that may be present in the object graph, the maximum number of graph items to serialize, parameters to ignore unexpected data, whether to use non-standard XML constructs to preserve object reference data in the graph, a surrogate for custom serialization, the XML element and namespace that contains the content, and an alternative for mapping xsi:type declarations at run time.

DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString)

初始化 DataContractSerializer 類別的新執行個體,以便序列化或還原序列化所指定型別的物件 (該型別會使用透過型別 XmlDictionaryString 之參數所指定的 XML 根項目和命名空間)。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type using the XML root element and namespace specified through the parameters of type XmlDictionaryString.

DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type. 這個方法也會透過兩個 XmlDictionaryString 參數來指定根 XML 項目和命名空間,以及可能存在於物件圖形內之已知型別的清單。This method also specifies the root XML element and namespace in two XmlDictionaryString parameters as well as a list of known types that may be present in the object graph.

DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type. 這個方法也會指定可能存在物件圖形中之已知型別的清單,要序列化之圖形項目的最大數,要略過非預期資料的參數,是否要使用非標準的 XML 建構來保存圖形中的物件參考資料,自訂序列化的代理,以及會指定其中含有內容之 XML 項目和命名空間的 XmlDictionaryString 參數。This method also specifies a list of known types that may be present in the object graph, the maximum number of graph items to serialize, parameters to ignore unexpected data, whether to use non-standard XML constructs to preserve object reference data in the graph, a surrogate for custom serialization, and parameters of XmlDictionaryString that specify the XML element and namespace that contain the content.

DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver) DataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString, IEnumerable<Type>, Int32, Boolean, Boolean, IDataContractSurrogate, DataContractResolver)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。Initializes a new instance of the DataContractSerializer class to serialize or deserialize an object of the specified type. 這個方法也會指定可能存在物件圖形中之已知型別的清單、要序列化之圖形項目的最大數、要略過非預期資料的參數、是否要使用非標準的 XML 建構來保存圖形中的物件參考資料、自訂序列化的代理、XmlDictionaryString 的參數 (會指定 XML 項目和包含內容的命名空間),以及在執行階段對應 xsi:type 宣告的替代方式。This method also specifies a list of known types that may be present in the object graph, the maximum number of graph items to serialize, parameters to ignore unexpected data, whether to use non-standard XML constructs to preserve object reference data in the graph, a surrogate for custom serialization, parameters of XmlDictionaryString that specify the XML element and namespace that contains the content, and an alternative for mapping xsi:type declarations at run time.

屬性

DataContractResolver DataContractResolver DataContractResolver DataContractResolver

取得用來將 xsi:type 宣告動態對應至已知合約型別的元件。Gets the component used to dynamically map xsi:type declarations to known contract types.

DataContractSurrogate DataContractSurrogate DataContractSurrogate DataContractSurrogate

取得可以擴充序列化或還原序列化程序的代理型別。Gets a surrogate type that can extend the serialization or deserialization process.

IgnoreExtensionDataObject IgnoreExtensionDataObject IgnoreExtensionDataObject IgnoreExtensionDataObject

取得值,這個值會指定當類別序列化或還原序列化時,是否略過類別延伸所提供的資料。Gets a value that specifies whether to ignore data supplied by an extension of the class when the class is being serialized or deserialized.

KnownTypes KnownTypes KnownTypes KnownTypes

取得型別的集合,這些型別可能會存在於使用這個 DataContractSerializer 執行個體所序列化的物件圖形中。Gets a collection of types that may be present in the object graph serialized using this instance of the DataContractSerializer.

MaxItemsInObjectGraph MaxItemsInObjectGraph MaxItemsInObjectGraph MaxItemsInObjectGraph

取得物件圖形中要序列化或還原序列化的最大項目數。Gets the maximum number of items in an object graph to serialize or deserialize.

PreserveObjectReferences PreserveObjectReferences PreserveObjectReferences PreserveObjectReferences

取得值,這個值會指定是否使用非標準的 XML 建構來保留物件參考資料。Gets a value that specifies whether to use non-standard XML constructs to preserve object reference data.

SerializeReadOnlyTypes SerializeReadOnlyTypes SerializeReadOnlyTypes SerializeReadOnlyTypes

取得值,指定是否序列化唯讀型別。Gets a value that specifies whether read-only types are serialized.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
IsStartObject(XmlDictionaryReader) IsStartObject(XmlDictionaryReader) IsStartObject(XmlDictionaryReader) IsStartObject(XmlDictionaryReader)

判斷 XmlDictionaryReader 是否置於可還原序列化的物件上。Determines whether the XmlDictionaryReader is positioned on an object that can be deserialized.

IsStartObject(XmlReader) IsStartObject(XmlReader) IsStartObject(XmlReader) IsStartObject(XmlReader)

判斷 XmlReader 是否置於可還原序列化的物件上。Determines whether the XmlReader is positioned on an object that can be deserialized.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ReadObject(Stream) ReadObject(Stream) ReadObject(Stream) ReadObject(Stream)

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

(Inherited from XmlObjectSerializer)
ReadObject(XmlDictionaryReader) ReadObject(XmlDictionaryReader) ReadObject(XmlDictionaryReader) ReadObject(XmlDictionaryReader)

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

(Inherited from XmlObjectSerializer)
ReadObject(XmlDictionaryReader, Boolean) ReadObject(XmlDictionaryReader, Boolean) ReadObject(XmlDictionaryReader, Boolean) ReadObject(XmlDictionaryReader, Boolean)

使用 XmlDictionaryReader 讀取 XML 資料流並傳回已還原序列化的物件,同時指定是否要先確認物件名稱,再讀取其值。Reads the XML stream with an XmlDictionaryReader and returns the deserialized object, and also specifies whether a check is made to verify the object name before reading its value.

ReadObject(XmlDictionaryReader, Boolean, DataContractResolver) ReadObject(XmlDictionaryReader, Boolean, DataContractResolver) ReadObject(XmlDictionaryReader, Boolean, DataContractResolver) ReadObject(XmlDictionaryReader, Boolean, DataContractResolver)

讀取 XML 文件或文件資料流,然後傳回已還原序列化的物件。Reads an XML document or document stream and returns the deserialized object. 這個方法包含一個參數 (指定要驗證的物件名稱是否已驗證),以及在執行階段對應 xsi:type 宣告的解析程式。The method includes a parameter to specify whether the object name is verified is validated, and a resolver for mapping xsi:type declarations at runtime.

ReadObject(XmlReader) ReadObject(XmlReader) ReadObject(XmlReader) ReadObject(XmlReader)

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

ReadObject(XmlReader, Boolean) ReadObject(XmlReader, Boolean) ReadObject(XmlReader, Boolean) ReadObject(XmlReader, Boolean)

使用 XmlReader 讀取 XML 資料流並傳回已還原序列化的物件,同時指定是否要先確認物件名稱,再讀取其值。Reads the XML stream with an XmlReader and returns the deserialized object, and also specifies whether a check is made to verify the object name before reading its value.

ToString() ToString() ToString() ToString()

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

(Inherited from Object)
WriteEndObject(XmlDictionaryWriter) WriteEndObject(XmlDictionaryWriter) WriteEndObject(XmlDictionaryWriter) WriteEndObject(XmlDictionaryWriter)

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

WriteEndObject(XmlWriter) WriteEndObject(XmlWriter) WriteEndObject(XmlWriter) WriteEndObject(XmlWriter)

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

WriteObject(Stream, Object) WriteObject(Stream, Object) WriteObject(Stream, Object) 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.

(Inherited from XmlObjectSerializer)
WriteObject(XmlDictionaryWriter, Object) WriteObject(XmlDictionaryWriter, Object) WriteObject(XmlDictionaryWriter, Object) 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.

(Inherited from XmlObjectSerializer)
WriteObject(XmlDictionaryWriter, Object, DataContractResolver) WriteObject(XmlDictionaryWriter, Object, DataContractResolver) WriteObject(XmlDictionaryWriter, Object, DataContractResolver) WriteObject(XmlDictionaryWriter, Object, DataContractResolver)

使用指定的 XmlDictionaryWriter,將所有的物件資料 (起始 XML 項目、內容及封入項目) 寫入至 XML 文件或資料流。Writes all the object data (starting XML element, content, and enclosing element) to an XML document or stream using the specified XmlDictionaryWriter. 此方法包括在執行階段對應 xsi:type 宣告的解析程式。The method includes a resolver for mapping xsi:type declarations at runtime.

WriteObject(XmlWriter, Object) WriteObject(XmlWriter, Object) WriteObject(XmlWriter, Object) WriteObject(XmlWriter, Object)

使用 XmlWriter,將所有的物件資料 (起始 XML 項目、內容以及結尾項目) 寫入至 XML 文件或資料流。Writes all the object data (starting XML element, content, and closing element) to an XML document or stream with an XmlWriter.

WriteObjectContent(XmlDictionaryWriter, Object) WriteObjectContent(XmlDictionaryWriter, Object) WriteObjectContent(XmlDictionaryWriter, Object) WriteObjectContent(XmlDictionaryWriter, Object)

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

WriteObjectContent(XmlWriter, Object) WriteObjectContent(XmlWriter, Object) WriteObjectContent(XmlWriter, Object) WriteObjectContent(XmlWriter, Object)

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

WriteStartObject(XmlDictionaryWriter, Object) WriteStartObject(XmlDictionaryWriter, Object) WriteStartObject(XmlDictionaryWriter, Object) WriteStartObject(XmlDictionaryWriter, Object)

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

WriteStartObject(XmlWriter, Object) WriteStartObject(XmlWriter, Object) WriteStartObject(XmlWriter, Object) WriteStartObject(XmlWriter, Object)

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

Extension Methods

GetSerializationSurrogateProvider(DataContractSerializer) GetSerializationSurrogateProvider(DataContractSerializer) GetSerializationSurrogateProvider(DataContractSerializer) GetSerializationSurrogateProvider(DataContractSerializer)

傳回此序列化程式的代理序列化提供者。Returns the surrogate serialization provider for this serializer.

SetSerializationSurrogateProvider(DataContractSerializer, ISerializationSurrogateProvider) SetSerializationSurrogateProvider(DataContractSerializer, ISerializationSurrogateProvider) SetSerializationSurrogateProvider(DataContractSerializer, ISerializationSurrogateProvider) SetSerializationSurrogateProvider(DataContractSerializer, ISerializationSurrogateProvider)

指定此 DataContractSerializer 的代理序列化提供者。Specifies a surrogate serialization provider for this DataContractSerializer.

適用於

執行緒安全性

此類別的執行個體都是執行緒安全以外的實作,當使用的執行個體IDataContractSurrogateDataContractResolverInstances of this class are thread safe except when the instance is used with an implementation of the IDataContractSurrogate or DataContractResolver.

另請參閱