KnownTypeAttribute 类

定义

指定 DataContractSerializer 在序列化或反序列化给定类型时应识别的类型。

public ref class KnownTypeAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=true)]
public sealed class KnownTypeAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=true)>]
type KnownTypeAttribute = class
    inherit Attribute
Public NotInheritable Class KnownTypeAttribute
Inherits Attribute
继承
KnownTypeAttribute
属性

示例

下面的示例演示了在序列化或反序列化 Person 类型时应识别的一个名为 IDInformation 的类型和一个名为 Person 的类型。

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Runtime.Serialization;

namespace KnownTypeAttributeExample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Serialize("KnownTypeAttributeExample.xml");
                Deserialize("KnownTypeAttributeExample.xml");
                // Run this twice. The second time, comment out the
                // Serialize call and comment out the
                // KnownTypeAttribute on the Person class. The
                // deserialization will then fail.
            }
            catch (SerializationException exc)
            {
                Console.WriteLine("{0}: {1}", exc.Message,
                    exc.StackTrace);
            }
            finally
            {
                Console.WriteLine("Press Enter to exit...");
                Console.ReadLine();
            }
        }

        public static void Serialize(string path)
        {
            Person p = new Person();
            p.Miscellaneous.Add(DateTime.Now, "Hello");
            p.Miscellaneous.Add(DateTime.Now.AddSeconds(1), "World");
            IDInformation w = new IDInformation();
            w.ID = "1111 00000";
            p.Miscellaneous.Add(DateTime.Now.AddSeconds(2), w);
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Person));
            FileStream fs = new FileStream(path, FileMode.Create);
            using (fs)
            {
                ser.WriteObject(fs, p);
            }
        }

        public static void Deserialize(string path)
        {
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Person));
            FileStream fs = new FileStream(path, FileMode.Open);
            using (fs)
            {
                Person p2 = (Person)ser.ReadObject(fs);
                Console.WriteLine("Count {0}", p2.Miscellaneous.Count);
                foreach (DictionaryEntry de in p2.Miscellaneous)
                {
                    Console.WriteLine("Key {0} Value: {1}", de.Key,
                    de.Value);
                    if (de.Value.GetType() == typeof(IDInformation))
                    {
                        IDInformation www = (IDInformation)de.Value;
                        Console.WriteLine(
                        "\t Found ID Information. ID: {0} \n", www.ID);
                    }
                }
            }
        }

        // Apply the KnownTypeAttribute to the class that
        // includes a member that returns a Hashtable.
        [KnownType(typeof(IDInformation))]
        [DataContract]
        public class Person : IExtensibleDataObject
        {
            private ExtensionDataObject ExtensionDataObjectValue;

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

            private Hashtable MiscellaneousValue = new Hashtable();
            [DataMember]
            public Hashtable Miscellaneous
            {
                get { return MiscellaneousValue; }
                set { MiscellaneousValue = value; }
            }
        }

        [DataContract]
        public class IDInformation : IExtensibleDataObject
        {
            private ExtensionDataObject ExtensionDataValue;
            public ExtensionDataObject ExtensionData
            {
                get { return ExtensionDataValue; }
                set { ExtensionDataValue = value; }
            }

            [DataMember]
            public string ID;
        }
    }
}
Imports System.Collections.Generic
Imports System.Collections
Imports System.Text
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Xml

Class Program

    Shared Sub Main(ByVal args() As String)
        Try
            Serialize("KnownTypeAttributeExample.xml")
            Deserialize("KnownTypeAttributeExample.xml")
            ' Run this twice. The second time, comment out the
            ' Serialize call and comment out the 
            ' KnownTypeAttribute on the Person class. The
            ' deserialization will then fail.
        Catch exc As SerializationException
            Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace)
        Finally
            Console.WriteLine("Press Enter to exit...")
            Console.ReadLine()
        End Try

    End Sub


    Public Shared Sub Serialize(ByVal path As String)
        Dim p As New Person()
        p.Miscellaneous.Add(DateTime.Now, "Hello")
        p.Miscellaneous.Add(DateTime.Now.AddSeconds(1), "World")
        Dim w As New IDInformation()
        w.ID = "1111 00000"
        p.Miscellaneous.Add(DateTime.Now.AddSeconds(2), w)
        Dim ser As New DataContractserializer(GetType(Person))
        Using fs As New FileStream(path, FileMode.OpenOrCreate)
            ser.WriteObject(fs, p)
        End Using
    End Sub

    Public Shared Sub Deserialize(ByVal path As String)
        Dim ser As New DataContractserializer(GetType(Person))
        Using fs As New FileStream(path, FileMode.OpenOrCreate)
            Dim p2 As Person = ser.ReadObject(fs)
            Console.WriteLine("Count {0}", p2.Miscellaneous.Count)
            For Each de As DictionaryEntry In p2.Miscellaneous
                Console.WriteLine("Key {0} Value: {1}", de.Key, _
                de.Value)
                If TypeOf (de.Value) Is IDInformation Then
                    Dim www As IDInformation = de.Value
                    Console.WriteLine( _
                    "Found ID Information. ID: {0}", www.ID)
                End If
            Next
        End Using
    End Sub

    ' Apply the KnownTypeAttribute to the class that 
    ' includes a member that returns a Hashtable.
    <System.Runtime.Serialization.KnownType(GetType(IDInformation))> _
    <DataContract()> _
    Public Class Person
        Implements IExtensibleDataObject
        Private MiscellaneousValue As New Hashtable()
        Private ExtensionDataObjectValue As ExtensionDataObject

        Public Property ExtensionData() As ExtensionDataObject _
            Implements IExtensibleDataObject.ExtensionData
            Get
                Return ExtensionDataObjectValue
            End Get
            Set(ByVal value As ExtensionDataObject)
                ExtensionDataObjectValue = value
            End Set
        End Property

        <DataMember()> _
        Public Property Miscellaneous() As Hashtable
            Get
                Return MiscellaneousValue
            End Get
            Set(ByVal value As Hashtable)
                MiscellaneousValue = value
            End Set
        End Property
    End Class

    <DataContract()> _
    Public Class IDInformation
        Implements IExtensibleDataObject

        Private ExtensionDataObjectValue As ExtensionDataObject

        Public Property ExtensionData() As ExtensionDataObject _
            Implements IExtensibleDataObject.ExtensionData
            Get
                Return ExtensionDataObjectValue
            End Get

            Set(ByVal value As ExtensionDataObject)
                ExtensionDataObjectValue = value
            End Set
        End Property

        <DataMember()> _
        Public ID As String
    End Class
End Class

注解

对某一类型应用 KnownTypeAttribute 属性,以便向 DataContractSerializer 指示在序列化或反序列化应用了该属性的类型的实例时应识别的类型。 该属性还可由其他理解数据协定的序列化程序识别。

备注

在代码中,可以使用 KnownType 一词来代替较长的 KnownTypeAttribute

您可以恰好应用一个设置了 KnownTypeAttribute 属性的 MethodName 实例,也可以应用一个或多个设置了 KnownTypeAttribute 属性的 Type 实例。

构造函数

KnownTypeAttribute(String)

使用能够返回已知类型的 KnownTypeAttribute 的方法的名称初始化 IEnumerable 类的新实例。

KnownTypeAttribute(Type)

使用指定的类型初始化 KnownTypeAttribute 类的新实例。

属性

MethodName

获取能够返回在序列化或反序列化过程中应识别的类型列表的方法名称。

Type

获取在 DataContractSerializer 进行序列化或反序列化的过程中应识别的类型。

TypeId

在派生类中实现时,获取此 Attribute 的唯一标识符。

(继承自 Attribute)

方法

Equals(Object)

返回一个值,该值指示此实例是否与指定的对象相等。

(继承自 Attribute)
GetHashCode()

返回此实例的哈希代码。

(继承自 Attribute)
GetType()

获取当前实例的 Type

(继承自 Object)
IsDefaultAttribute()

在派生类中重写时,指示此实例的值是否是派生类的默认值。

(继承自 Attribute)
Match(Object)

当在派生类中重写时,返回一个指示此实例是否等于指定对象的值。

(继承自 Attribute)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

显式接口实现

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

将一组名称映射为对应的一组调度标识符。

(继承自 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。

(继承自 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。

(继承自 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对某一对象公开的属性和方法的访问。

(继承自 Attribute)

适用于

另请参阅