本文由机器翻译。若要查看英语原文,请勾选“英语”复选框。 也可将鼠标指针移到文本上,在弹出窗口中显示英语原文。
翻译
英语

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 结构来保留对象引用数据在关系图、 自定义序列化的代理项和映射的备用 xsi:type 在运行时的声明。

System_CAPS_pubmethodDataContractSerializer(Type, String, String)

使用提供的 XML 根元素和命名空间初始化 DataContractSerializer 类的新实例,以便序列化或反序列化指定类型的对象。

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 的参数指定的 XML 根元素和命名空间初始化 XmlDictionaryString 类的新实例,以便序列化或反序列化指定类型的对象。

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 结构来保留对象引用数据在图中,自定义序列化的参数的代理项 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)

使用 XmlDictionaryWriter 写入结束 XML 元素。(覆盖 XmlObjectSerializer.WriteEndObject(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.

返回页首
显示: