Classe KnownTypeAttribute (System.Runtime.Serialization)

Cambia visualizzazione:
ScriptFree
Riferimento a .NET Framework
Classe KnownTypeAttribute
Il presente articolo è stato tradotto manualmente. Per visualizzare questa pagina e contemporaneamente visualizzarne il contenuto in lingua inglese, passare alla visualizzazione semplificata.

Specifica i tipi che devono essere riconosciuti dalla classe DataContractSerializer durante la serializzazione o deserializzazione di un tipo specifico.

Gerarchia di ereditarietà

System.Object
  System.Attribute
    System.Runtime.Serialization.KnownTypeAttribute

Spazio dei nomi:  System.Runtime.Serialization
Assembly:  System.Runtime.Serialization (in System.Runtime.Serialization.dll)
Sintassi

Visual Basic
<AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Struct, Inherited := True,  _
	AllowMultiple := True)> _
Public NotInheritable Class KnownTypeAttribute _
	Inherits Attribute
C#
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Struct, Inherited = true, 
	AllowMultiple = true)]
public sealed class KnownTypeAttribute : Attribute
Visual C++
[AttributeUsageAttribute(AttributeTargets::Class|AttributeTargets::Struct, Inherited = true, 
	AllowMultiple = true)]
public ref class KnownTypeAttribute sealed : public Attribute
F#
[<Sealed>]
[<AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Struct, Inherited = true, 
    AllowMultiple = true)>]
type KnownTypeAttribute =  
    class
        inherit Attribute
    end

Il tipo KnownTypeAttribute espone i seguenti membri.

Costruttori

  Nome Descrizione
Metodo pubblico ms574983.PortableClassLibrary(it-it,VS.100).gif KnownTypeAttribute(String) Inizializza una nuova istanza della classe KnownTypeAttribute con il nome di un metodo che restituisce un'interfaccia IEnumerable di tipi noti.
Metodo pubblico ms574983.PortableClassLibrary(it-it,VS.100).gif KnownTypeAttribute(Type) Inizializza una nuova istanza della classe KnownTypeAttribute con il tipo specificato.
In alto
Proprietà

  Nome Descrizione
Proprietà pubblica ms574983.PortableClassLibrary(it-it,VS.100).gif MethodName Ottiene il nome di un metodo che restituirà un elenco di tipi che devono essere riconosciuti durante la serializzazione o deserializzazione.
Proprietà pubblica ms574983.PortableClassLibrary(it-it,VS.100).gif Type Ottiene il tipo che deve essere riconosciuto durante la serializzazione o deserializzazione da parte della classe DataContractSerializer.
Proprietà pubblica TypeId Quando è implementata in una classe derivata, ottiene un identificatore univoco della classe Attribute. (Ereditato da Attribute)
In alto
Metodi

  Nome Descrizione
Metodo pubblico ms574983.PortableClassLibrary(it-it,VS.100).gif Equals Infrastruttura. Restituisce un valore che indica se l'istanza è uguale a un oggetto specificato. (Ereditato da Attribute)
Metodo protetto ms574983.PortableClassLibrary(it-it,VS.100).gif Finalize Consente a un oggetto di provare a liberare risorse ed eseguire altre operazioni di pulitura prima che l'oggetto stesso venga recuperato dalla procedura di Garbage Collection. (Ereditato da Object)
Metodo pubblico ms574983.PortableClassLibrary(it-it,VS.100).gif GetHashCode Restituisce il codice hash per l'istanza. (Ereditato da Attribute)
Metodo pubblico ms574983.PortableClassLibrary(it-it,VS.100).gif GetType Ottiene l'oggetto Type dell'istanza corrente. (Ereditato da Object)
Metodo pubblico IsDefaultAttribute Quando è sottoposto a override in una classe derivata, indica se il valore di questa istanza è il valore predefinito della classe derivata. (Ereditato da Attribute)
Metodo pubblico Match Quando è sottoposto a override in una classe derivata, restituisce un valore che indica se questa istanza equivale a un oggetto specificato. (Ereditato da Attribute)
Metodo protetto ms574983.PortableClassLibrary(it-it,VS.100).gif MemberwiseClone Consente di creare una copia dei riferimenti dell'oggetto Object corrente. (Ereditato da Object)
Metodo pubblico ms574983.PortableClassLibrary(it-it,VS.100).gif ToString Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object)
In alto
Implementazioni esplicite dell'interfaccia

  Nome Descrizione
Implementazione esplicita dell'interfaccia Metodo privato _Attribute.GetIDsOfNames Esegue il mapping di un set di nomi a un set corrispondente di ID di invio. (Ereditato da Attribute)
Implementazione esplicita dell'interfaccia Metodo privato _Attribute.GetTypeInfo Recupera le informazioni sul tipo relative a un oggetto, che possono essere utilizzate per ottenere informazioni sul tipo relative a un'interfaccia. (Ereditato da Attribute)
Implementazione esplicita dell'interfaccia Metodo privato _Attribute.GetTypeInfoCount Recupera il numero delle interfacce di informazioni di tipo fornite da un oggetto (0 o 1). (Ereditato da Attribute)
Implementazione esplicita dell'interfaccia Metodo privato _Attribute.Invoke Fornisce l'accesso a proprietà e metodi esposti da un oggetto. (Ereditato da Attribute)
In alto
Note

Applicare l'attributo KnownTypeAttribute a un tipo per indicare i tipi DataContractSerializer che devono essere riconosciuti durante la serializzazione o deserializzazione di un'istanza del tipo alla quale è applicato l'attributo. Questo attributo può essere riconosciuto anche da altri serializzatori in grado di interpretare i contratti dati.

Nota Nota

Nel codice è possibile utilizzare KnownType anziché la forma estesa KnownTypeAttribute.

È possibile applicare esattamente un'istanza di KnownTypeAttribute con la proprietà MethodName impostata oppure una o più istanze di KnownTypeAttribute con la proprietà Type impostata.

Esempi

Nell'esempio seguente viene illustrato un tipo denominato Person e un tipo denominato IDInformation che devono essere riconosciuti durante la serializzazione o la deserializzazione del tipo Person.

Visual Basic

Imports System
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


C#

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;
        }
    }
}


Informazioni sulla versione

.NET Framework

Supportato in: 4, 3.5, 3.0

.NET Framework Client Profile

Supportato in: 4, 3.5 SP1

Supportato in:
Piattaforme

Windows 7, Windows Vista SP1 o versione successiva, Windows XP SP3, Windows Server 2008 (componenti di base del server non supportati), Windows Server 2008 R2 (componenti di base del server supportati con SP1 o versione successiva), Windows Server 2003 SP2

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema di .NET Framework.
Codice thread safe

Qualsiasi membro static (Shared in Visual Basic) pubblico di questo tipo è thread-safe. I membri di istanza non sono garantiti come thread-safe.
Vedere anche

Riferimenti