本文為機器翻譯文章。如需檢視英文版,請選取 [原文] 核取方塊。您也可以將滑鼠指標移到文字上,即可在快顯視窗顯示英文原文。
譯文
原文

DataContractSerializer 類別

 

將某個型別的執行個體序列化及還原序列化成使用所提供資料合約的 XML 資料流或文件。 此類別無法被繼承。

命名空間:   System.Runtime.Serialization
組件:  System.Runtime.Serialization (於 System.Runtime.Serialization.dll)

System.Object
  System.Runtime.Serialization.XmlObjectSerializer
    System.Runtime.Serialization.DataContractSerializer

public sealed class DataContractSerializer : XmlObjectSerializer

名稱描述
System_CAPS_pubmethodDataContractSerializer(Type)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。

System_CAPS_pubmethodDataContractSerializer(Type, DataContractSerializerSettings)

初始化的新執行個體 DataContractSerializer 類別來序列化或還原序列化指定型別和設定的物件。

System_CAPS_pubmethodDataContractSerializer(Type, IEnumerable<Type>)

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件,以及可能存在物件圖形中的已知型別集合。

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

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。 這個方法也會指定可能存在物件圖形中之已知型別的清單,要序列化之圖形項目的最大數,要略過非預期資料的參數,是否要使用非標準的 XML 建構來保存圖形中的物件參考資料,以及自訂序列化的代理。

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

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。 這個方法也會指定可能存在物件圖形序列化,要略過非預期的資料參數的圖形項目數目上限中之已知型別的清單、 是否要使用非標準的 XML 建構來保留物件參考資料,在圖形、 自訂的序列化的 surrogate 索引鍵和對應的替代選項 xsi:type 在執行階段的宣告。

System_CAPS_pubmethodDataContractSerializer(Type, String, String)

初始化 DataContractSerializer 類別的新執行個體,以便序列化或還原序列化已指定型別的物件 (該型別會使用提供的 XML 根項目和命名空間)。

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

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。 這個方法也會透過兩個字串參數來指定根 XML 項目和命名空間,以及可能存在於物件圖形內之已知型別的清單。

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

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。 這個方法也會指定可能存在物件圖形中之已知型別的清單、要序列化之圖形項目的最大數、要略過非預期資料的參數、是否要使用非標準的 XML 建構來保存圖形中的物件參考資料、自訂序列化的代理,以及含有內容的 XML 項目和命名空間。

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

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。 這個方法也會指定可能存在物件圖形序列化,要略過非預期的資料參數的圖形項目數目上限中之已知型別的清單、 是否要使用非標準的 XML 建構來保留物件參考資料,在圖形中,自訂序列化、 XML 項目和命名空間包含的內容和對應的替代代理 xsi:type 在執行階段的宣告。

System_CAPS_pubmethodDataContractSerializer(Type, XmlDictionaryString, XmlDictionaryString)

初始化 DataContractSerializer 類別的新執行個體,以便序列化或還原序列化所指定型別的物件 (該型別會使用透過型別 XmlDictionaryString 之參數所指定的 XML 根項目和命名空間)。

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

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。 這個方法也會透過兩個 XmlDictionaryString 參數來指定根 XML 項目和命名空間,以及可能存在於物件圖形內之已知型別的清單。

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

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。 這個方法也會指定可能存在物件圖形中之已知型別的清單,要序列化之圖形項目的最大數,要略過非預期資料的參數,是否要使用非標準的 XML 建構來保存圖形中的物件參考資料,自訂序列化的代理,以及會指定其中含有內容之 XML 項目和命名空間的 XmlDictionaryString 參數。

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

初始化 DataContractSerializer 類別的新執行個體,以序列化或還原序列化所指定型別的物件。 這個方法也會指定可能存在物件圖形序列化,要略過非預期的資料參數的圖形項目數目上限中之已知型別的清單、 是否要使用非標準的 XML 建構來保留物件參考資料,在圖形中,自訂序列化,參數的 surrogate XmlDictionaryString 指定的 XML 項目和命名空間包含的內容與對應的替代選項 xsi:type 在執行階段的宣告。

名稱描述
System_CAPS_pubpropertyDataContractResolver

取得用於動態對應的元件 xsi:type 至已知的合約型別宣告。

System_CAPS_pubpropertyDataContractSurrogate

取得可以擴充序列化或還原序列化程序的代理型別。

System_CAPS_pubpropertyIgnoreExtensionDataObject

取得值,這個值會指定當類別序列化或還原序列化時,是否略過類別延伸所提供的資料。

System_CAPS_pubpropertyKnownTypes

取得型別的集合,這些型別可能會存在於使用這個 DataContractSerializer 執行個體所序列化的物件圖形中。

System_CAPS_pubpropertyMaxItemsInObjectGraph

取得物件圖形中要序列化或還原序列化的最大項目數。

System_CAPS_pubpropertyPreserveObjectReferences

取得值,這個值會指定是否使用非標準的 XML 建構來保留物件參考資料。

System_CAPS_pubpropertySerializeReadOnlyTypes

取得值,指定是否唯讀型別的序列化。

名稱描述
System_CAPS_pubmethodEquals(Object)

判斷指定的物件是否等於目前的物件。(繼承自 Object。)

System_CAPS_pubmethodGetHashCode()

做為預設雜湊函式。(繼承自 Object。)

System_CAPS_pubmethodGetType()

取得目前執行個體的 Type(繼承自 Object。)

System_CAPS_pubmethodIsStartObject(XmlDictionaryReader)

判斷 XmlDictionaryReader 是否置於可還原序列化的物件上。(覆寫 XmlObjectSerializer.IsStartObject(XmlDictionaryReader)。)

System_CAPS_pubmethodIsStartObject(XmlReader)

判斷 XmlReader 是否置於可還原序列化的物件上。(覆寫 XmlObjectSerializer.IsStartObject(XmlReader)。)

System_CAPS_pubmethodReadObject(Stream)

使用 Stream 讀取 XML 資料流或文件,然後傳回已還原序列化的物件。(繼承自 XmlObjectSerializer。)

System_CAPS_pubmethodReadObject(XmlDictionaryReader)

使用 XmlDictionaryReader 讀取 XML 文件或資料流,然後傳回已還原序列化的物件。(繼承自 XmlObjectSerializer。)

System_CAPS_pubmethodReadObject(XmlDictionaryReader, Boolean)

使用 XmlDictionaryReader 讀取 XML 資料流並傳回已還原序列化的物件,同時指定是否要先確認物件名稱,再讀取其值。(覆寫 XmlObjectSerializer.ReadObject(XmlDictionaryReader, Boolean)。)

System_CAPS_pubmethodReadObject(XmlDictionaryReader, Boolean, DataContractResolver)

讀取 XML 文件或文件資料流,然後傳回已還原序列化的物件。 此方法包含參數,以指定的物件名稱是否已驗證進行驗證,以及對應的解析程式 xsi:type 在執行階段的宣告。

System_CAPS_pubmethodReadObject(XmlReader)

使用 XmlReader 讀取 XML 資料流,然後傳回已還原序列化的物件。(覆寫 XmlObjectSerializer.ReadObject(XmlReader)。)

System_CAPS_pubmethodReadObject(XmlReader, Boolean)

使用 XmlReader 讀取 XML 資料流並傳回已還原序列化的物件,同時指定是否要先確認物件名稱,再讀取其值。(覆寫 XmlObjectSerializer.ReadObject(XmlReader, Boolean)。)

System_CAPS_pubmethodToString()

傳回代表目前物件的字串。(繼承自 Object。)

System_CAPS_pubmethodWriteEndObject(XmlDictionaryWriter)
System_CAPS_pubmethodWriteEndObject(XmlWriter)

使用 XmlWriter 寫入結尾 XML 項目。(覆寫 XmlObjectSerializer.WriteEndObject(XmlWriter)。)

System_CAPS_pubmethodWriteObject(Stream, Object)

使用指定的 Stream,將物件的完整內容 (開始、內容和結束) 寫入至 XML 文件或資料流。(繼承自 XmlObjectSerializer。)

System_CAPS_pubmethodWriteObject(XmlDictionaryWriter, Object)

使用指定的 XmlDictionaryWriter,將物件的完整內容 (開始、內容和結束) 寫入至 XML 文件或資料流。(繼承自 XmlObjectSerializer。)

System_CAPS_pubmethodWriteObject(XmlDictionaryWriter, Object, DataContractResolver)

使用指定的 XmlDictionaryWriter,將所有的物件資料 (起始 XML 項目、內容及封入項目) 寫入至 XML 文件或資料流。 此方法包含對應的解析程式 xsi:type 在執行階段的宣告。

System_CAPS_pubmethodWriteObject(XmlWriter, Object)

使用 XmlWriter,將所有的物件資料 (起始 XML 項目、內容以及結尾項目) 寫入至 XML 文件或資料流。(覆寫 XmlObjectSerializer.WriteObject(XmlWriter, Object)。)

System_CAPS_pubmethodWriteObjectContent(XmlDictionaryWriter, Object)
System_CAPS_pubmethodWriteObjectContent(XmlWriter, Object)
System_CAPS_pubmethodWriteStartObject(XmlDictionaryWriter, Object)
System_CAPS_pubmethodWriteStartObject(XmlWriter, Object)

使用 XmlWriter 寫入開頭 XML 項目。(覆寫 XmlObjectSerializer.WriteStartObject(XmlWriter, Object)。)

Use the T:System.Runtime.Serialization.DataContractSerializer class to serialize and deserialize instances of a type into an XML stream or document. For example, you can create a type named Person with properties that contain essential data, such as a name and address. 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. Most important, the T:System.Runtime.Serialization.DataContractSerializer is used to serialize and deserialize data sent in indigo1 messages. Apply the T:System.Runtime.Serialization.DataContractAttribute attribute to classes, and the T:System.Runtime.Serialization.DataMemberAttribute attribute to class members to specify properties and fields that are serialized.

如需清單 types that can be serialized, see 資料合約序列化程式支援的型別.

To use the T:System.Runtime.Serialization.DataContractSerializer, first create an instance of a class and an object appropriate to writing or reading the format; for example, an instance of the T:System.Xml.XmlDictionaryWriter. Then call the M:System.Runtime.Serialization.XmlObjectSerializer.WriteObject(System.Xml.XmlDictionaryWriter,System.Object) method to persist the data. To retrieve data, create an object appropriate to reading the data format (such as an T:System.Xml.XmlDictionaryReader for an XML document) and call the Overload:System.Runtime.Serialization.DataContractSerializer.ReadObject method.

如需詳細資訊 using the DataContractSerializer, see 序列化和還原序列化.

You can set the type of a data contract serializer using the <dataContractSerializer> element in a client application configuration file.

The T:System.Runtime.Serialization.DataContractSerializer is used in combination with the T:System.Runtime.Serialization.DataContractAttribute and T:System.Runtime.Serialization.DataMemberAttribute classes. To prepare a class for serialization, apply the T:System.Runtime.Serialization.DataContractAttribute to the class. For each member of the class that returns data that you want to serialize, apply the T:System.Runtime.Serialization.DataMemberAttribute. You can serialize fields and properties, regardless of accessibility: private, protected, internal, protected internal, or public.

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. To create a type that conforms to the contract, first apply the T:System.Runtime.Serialization.DataContractAttribute to the class. Then apply the T:System.Runtime.Serialization.DataMemberAttribute to every field or property that you want to serialize.

System_CAPS_note注意

You can apply the T:System.Runtime.Serialization.DataMemberAttribute to both private and public members.

The final format of the XML need not be text. Instead, the T:System.Runtime.Serialization.DataContractSerializer writes the data as an XML infoset, which allows you to write the data to any format recognized by the T:System.Xml.XmlReader and T:System.Xml.XmlWriter. It is recommended that you use the T:System.Xml.XmlDictionaryReader and T:System.Xml.XmlDictionaryWriter classes to read and write, because both are optimized to work with the T:System.Runtime.Serialization.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.

When serializing or deserializing an object, it is required that the type is "known" to the T:System.Runtime.Serialization.DataContractSerializer. Begin by creating an instance of a class that implements T:System.Collections.Generic.IEnumerable`1 (such as T:System.Collections.Generic.List`1) and adding the known types to the collection. Then create an instance of the T:System.Runtime.Serialization.DataContractSerializer using one of the overloads that takes the T:System.Collections.Generic.IEnumerable`1 (for example, M:System.Runtime.Serialization.DataContractSerializer.#ctor(System.Type,System.Collections.Generic.IEnumerable{System.Type}).

System_CAPS_note注意

Unlike other primitive types, the T:System.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).

The T:System.Runtime.Serialization.DataContractSerializer understands data contracts that have been designed to be compatible with future versions of the contract. Such types implement the T:System.Runtime.Serialization.IExtensibleDataObject interface. The interface features the P:System.Runtime.Serialization.IExtensibleDataObject.ExtensionData property that returns an T:System.Runtime.Serialization.ExtensionDataObject object. crdefaultForward Compatible Data Contracts.

When instantiating the target object during deserialization, the T:System.Runtime.Serialization.DataContractSerializer does not call the constructor of the target object. 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:

  • 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.

  • If you code the class that assumes the constructor has run, the class may get into an invalid internal state that is exploitable.

The following example code shows a type named Person that is serialized by the T:System.Runtime.Serialization.DataContractSerializer. The T:System.Runtime.Serialization.DataContractAttribute attribute is applied to the class, and the T:System.Runtime.Serialization.DataMemberAttribute is applied to members to instruct the T:System.Runtime.Serialization.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));
        }
    }

通用 Windows 平台
自 8 起供應
.NET Framework
自 3.0 起供應
可攜式類別庫
提供支援︰ 可攜式 .NET 平台
Silverlight
自 2.0 起供應
Windows Phone Silverlight
自 7.0 起供應
Windows Phone
自 8.1 起供應

Instances of this class are thread safe except when the instance is used with an implementation of the T:System.Runtime.Serialization.IDataContractSurrogate or T:System.Runtime.Serialization.DataContractResolver.

回到頁首
顯示: