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 に指示します。 データ コントラクトを理解する他のシリアライザーも、この属性を認識できます。

Note

コードでは、KnownType の代わりに KnownTypeAttribute という短い語を使用できます。

KnownTypeAttribute プロパティを設定して MethodName インスタンスを 1 つだけ適用するか、または KnownTypeAttribute プロパティを設定して 1 つ以上の 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)

適用対象

こちらもご覧ください