KnownTypeAttribute Klas

Definitie

Hiermee geeft u typen op die moeten worden herkend bij het DataContractSerializer serialiseren of deserialiseren van een bepaald type.

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
Overname
KnownTypeAttribute
Kenmerken

Voorbeelden

In het volgende voorbeeld ziet u een type met de naam Person en een type dat IDInformation moet worden herkend bij het serialiseren of deserialiseren van het Person type.

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

Opmerkingen

Pas het KnownTypeAttribute kenmerk toe op een type om aan te geven op de DataContractSerializer typen die moeten worden herkend bij het serialiseren of deserialiseren van een exemplaar van het type waarop het kenmerk wordt toegepast. Dit kenmerk kan ook worden herkend door andere serializers die inzicht hebben in gegevenscontracten.

Note

In uw code kunt u het woord KnownType gebruiken in plaats van langer KnownTypeAttribute.

U kunt exact één KnownTypeAttribute exemplaar toepassen met de MethodName eigenschappenset of een of meer KnownTypeAttribute exemplaren met de Type eigenschappenset.

Constructors

Name Description
KnownTypeAttribute(String)

Initialiseert een nieuw exemplaar van de KnownTypeAttribute klasse met de naam van een methode die een IEnumerable van de bekende typen retourneert.

KnownTypeAttribute(Type)

Initialiseert een nieuw exemplaar van de KnownTypeAttribute klasse met het opgegeven type.

Eigenschappen

Name Description
MethodName

Hiermee haalt u de naam op van een methode die een lijst met typen retourneert die moeten worden herkend tijdens serialisatie of deserialisatie.

Type

Hiermee haalt u het type op dat moet worden herkend tijdens serialisatie of deserialisatie door de DataContractSerializer.

TypeId

Wanneer deze wordt geïmplementeerd in een afgeleide klasse, krijgt u Attributehiervoor een unieke id.

(Overgenomen van Attribute)

Methoden

Name Description
Equals(Object)

Retourneert een waarde die aangeeft of dit exemplaar gelijk is aan een opgegeven object.

(Overgenomen van Attribute)
GetHashCode()

Retourneert de hash-code voor dit exemplaar.

(Overgenomen van Attribute)
GetType()

Hiermee haalt u de Type huidige instantie op.

(Overgenomen van Object)
IsDefaultAttribute()

Wanneer deze wordt overschreven in een afgeleide klasse, geeft u aan of de waarde van dit exemplaar de standaardwaarde is voor de afgeleide klasse.

(Overgenomen van Attribute)
Match(Object)

Wanneer deze wordt overschreven in een afgeleide klasse, wordt een waarde geretourneerd die aangeeft of dit exemplaar gelijk is aan een opgegeven object.

(Overgenomen van Attribute)
MemberwiseClone()

Hiermee maakt u een ondiepe kopie van de huidige Object.

(Overgenomen van Object)
ToString()

Retourneert een tekenreeks die het huidige object vertegenwoordigt.

(Overgenomen van Object)

Expliciete interface-implementaties

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

Hiermee wordt een set namen toegewezen aan een bijbehorende set verzend-id's.

(Overgenomen van Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Hiermee haalt u de typegegevens voor een object op, die kan worden gebruikt om de typegegevens voor een interface op te halen.

(Overgenomen van Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Hiermee wordt het aantal type-informatieinterfaces opgehaald dat een object biedt (0 of 1).

(Overgenomen van Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Biedt toegang tot eigenschappen en methoden die door een object worden weergegeven.

(Overgenomen van Attribute)

Van toepassing op

Zie ook