KnownTypeAttribute Classe
Définition
Spécifie les types qui doivent être reconnus par le DataContractSerializer lors de la sérialisation ou de la désérialisation d'un type donné.Specifies types that should be recognized by the DataContractSerializer when serializing or deserializing a given type.
public ref class KnownTypeAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=true)]
public sealed class KnownTypeAttribute : Attribute
type KnownTypeAttribute = class
inherit Attribute
Public NotInheritable Class KnownTypeAttribute
Inherits Attribute
- Héritage
- Attributs
Exemples
L'exemple suivant illustre un type nommé Person
et un type nommé IDInformation
qui doivent être reconnus lors de la sérialisation ou de la désérialisation du type Person
.The following example shows a type named Person
and a type named IDInformation
that should be recognized when serializing or deserializing the 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
Remarques
Appliquez l'attribut KnownTypeAttribute à un type pour indiquer au DataContractSerializer les types qui doivent être reconnus lors de la sérialisation ou de la désérialisation d'une instance du type auquel l'attribut est appliqué.Apply the KnownTypeAttribute attribute to a type to indicate to the DataContractSerializer types that should be recognized when serializing or deserializing an instance of the type to which the attribute is applied. Cet attribut pourrait également être reconnu par les d'autres sérialiseurs qui comprennent des contrats de données.This attribute could also be recognized by other serializers that understand data contracts.
Notes
Dans votre code, vous pouvez utiliser le mot KnownType
à la place de KnownTypeAttribute
qui est plus long.In your code, you can use the word KnownType
instead of the longer KnownTypeAttribute
.
Vous pouvez appliquer une seule instance KnownTypeAttribute avec le jeu de propriétés MethodName ou un ou plusieurs instances KnownTypeAttribute avec le jeu de propriétés Type.You can either apply exactly one KnownTypeAttribute instance with the MethodName property set, or one or more KnownTypeAttribute instances with the Type property set.
Constructeurs
KnownTypeAttribute(String) |
Initialise une nouvelle instance de la classe KnownTypeAttribute avec le nom d'une méthode qui retourne un IEnumerable des types connus.Initializes a new instance of the KnownTypeAttribute class with the name of a method that returns an IEnumerable of known types. |
KnownTypeAttribute(Type) |
Initialise une nouvelle instance de la classe KnownTypeAttribute à l'aide du type spécifié.Initializes a new instance of the KnownTypeAttribute class with the specified type. |
Propriétés
MethodName |
Obtient le nom d'une méthode qui retournera une liste des types qui doivent être reconnus lors de la sérialisation ou de la désérialisation.Gets the name of a method that will return a list of types that should be recognized during serialization or deserialization. |
Type |
Obtient le type qui doit être reconnu lors de la sérialisation ou de la désérialisation par le DataContractSerializer.Gets the type that should be recognized during serialization or deserialization by the DataContractSerializer. |
TypeId |
Lors de l'implémentation dans une classe dérivée, obtient un identificateur unique pour l'objet Attribute.When implemented in a derived class, gets a unique identifier for this Attribute. (Hérité de Attribute) |
Méthodes
Equals(Object) |
Retourne une valeur qui indique si cette instance est égale à un objet spécifié.Returns a value that indicates whether this instance is equal to a specified object. (Hérité de Attribute) |
GetHashCode() |
Retourne le code de hachage de cette instance.Returns the hash code for this instance. (Hérité de Attribute) |
GetType() |
Obtient le Type de l'instance actuelle.Gets the Type of the current instance. (Hérité de Object) |
IsDefaultAttribute() |
En cas de substitution dans une classe dérivée, indique si la valeur de cette instance est la valeur par défaut pour la classe dérivée.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Hérité de Attribute) |
Match(Object) |
En cas de substitution dans une classe dérivée, retourne une valeur indiquant si cette instance équivaut à un objet spécifié.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Hérité de Attribute) |
MemberwiseClone() |
Crée une copie superficielle du Object actuel.Creates a shallow copy of the current Object. (Hérité de Object) |
ToString() |
Retourne une chaîne qui représente l'objet en cours.Returns a string that represents the current object. (Hérité de Object) |
Implémentations d’interfaces explicites
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch.Maps a set of names to a corresponding set of dispatch identifiers. (Hérité de Attribute) |
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Récupère les informations de type pour un objet, qui peuvent être utilisées pour obtenir les informations de type d'une interface.Retrieves the type information for an object, which can be used to get the type information for an interface. (Hérité de Attribute) |
_Attribute.GetTypeInfoCount(UInt32) |
Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Hérité de Attribute) |
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fournit l'accès aux propriétés et aux méthodes exposées par un objet.Provides access to properties and methods exposed by an object. (Hérité de Attribute) |