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. 因此,以下代码将失败,并出现异常: "Root 类型" System.xml.linq.xelement> "在顶级不支持 NetDataContractSerializer,因为它与 IsAny=是 IXmlSerializable 的 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.

适用于

另请参阅