KnownTypeAttribute 생성자

정의

KnownTypeAttribute 클래스의 새 인스턴스를 초기화합니다.

오버로드

KnownTypeAttribute(String)

알려진 형식의 KnownTypeAttribute을 반환하는 메서드의 이름을 사용하여 IEnumerable 클래스의 새 인스턴스를 초기화합니다.

KnownTypeAttribute(Type)

지정된 형식을 사용하여 KnownTypeAttribute 클래스의 새 인스턴스를 초기화합니다.

KnownTypeAttribute(String)

알려진 형식의 KnownTypeAttribute을 반환하는 메서드의 이름을 사용하여 IEnumerable 클래스의 새 인스턴스를 초기화합니다.

public:
 KnownTypeAttribute(System::String ^ methodName);
public KnownTypeAttribute (string methodName);
new System.Runtime.Serialization.KnownTypeAttribute : string -> System.Runtime.Serialization.KnownTypeAttribute
Public Sub New (methodName As String)

매개 변수

methodName
String

데이터를 직렬화 또는 역직렬화할 때 사용된 형식의 IEnumerable을 반환하는 메서드의 이름입니다.

예제

다음 예제에서는 매개 변수를 methodName 사용하여 개체 배열이 포함된 형식의 Type 메서드를 식별합니다.

namespace KnownTypeAttributeExample
{
    using System;
    using System.Xml;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.Serialization;
    using System.IO;
    // The constructor names the method that returns an array
    // of types that can be used during deserialization.
    [KnownTypeAttribute("KnownTypes")]
    [DataContract]
    public class Employee
    {
        public Employee(string newFName, string newLName)
        {
            FirstName = newFName;
            LastName = newLName;
        }
        [DataMember]
        internal string FirstName;
        [DataMember]
        internal string LastName;
        [DataMember]
        internal int id;
        [DataMember]
        internal Manager Boss;

        // This method returns the array of known types.
        static Type[] KnownTypes()
        {
            return new Type[]{typeof(Manager), typeof(Employee)};
        }
    }

    [DataContract]
    public class Manager : Employee
    {
        // Call the base class's constructor.
        public Manager(string newFName, string newLName)
            : base(newFName, newLName)
        { }

        [DataMember]
        internal Employee[] Reports;
    }

    class Program
    {
        public static void Main()
        {
            try
            {
                Serialize("person1.xml");
                Deserialize("person1.xml");
            }
            catch (SerializationException se)
            {
                Console.WriteLine("{0}: {1}",
                se.Message, se.StackTrace);
            }
            finally
            {
                Console.WriteLine("Press Enter to exit....");
                Console.ReadLine();
            }
        }

        static void Serialize(string path)
        {
            Employee emp = new Employee("John", "Peoples");
            emp.id = 3001;
            Manager theBoss = new Manager("Michiyo", "Sato");
            theBoss.id = 41;
            emp.Boss = theBoss;

            DataContractSerializer ser =
                new DataContractSerializer(typeof(Employee));

            FileStream fs =
                new FileStream(path, FileMode.OpenOrCreate);
            ser.WriteObject(fs, emp);
            fs.Close();
        }
        static void Deserialize(string path)
        {
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Employee));
            FileStream fs = new FileStream(path,
            FileMode.Open);
            Employee p = (Employee)ser.ReadObject(fs);

            Console.WriteLine("{0} {1}, id:{2}", p.FirstName,
                p.LastName, p.id);
            fs.Close();
        }
    }
}
' The constructor names the method that returns an array 
' of types that can be used during deserialization.
<KnownTypeAttribute("KnownTypes"), DataContract()>  _
Public Class Employee
    Public Sub New(ByVal newFName As String, ByVal newLName As String) 
        FirstName = newFName
        LastName = newLName
    
    End Sub
    <DataMember()>  _
    Friend FirstName As String
    <DataMember()>  _
    Friend LastName As String
    <DataMember()>  _
    Friend id As Integer
    <DataMember()>  _
    Friend Boss As Manager
    
    ' This method returns the array of known types.
    Shared Function KnownTypes() As Type() 
        Return New Type() {GetType(Manager), GetType(Employee)}
    
    End Function 
End Class 

<DataContract()>  _
Public Class Manager
    Inherits Employee
    
    ' Call the base class's constructor.
    Public Sub New(ByVal newFName As String, ByVal newLName As String) 
        MyBase.New(newFName, newLName)
    
    End Sub 
    
    <DataMember()>  _
    Friend Reports() As Employee
End Class 

Class Program

    Public Shared Sub Main() 
        Try
            Serialize("person1.xml")
            Deserialize("person1.xml")
        Catch se As SerializationException
            Console.WriteLine("{0}: {1}", se.Message, se.StackTrace)
        Finally
            Console.WriteLine("Press Enter to exit....")
            Console.ReadLine()
        End Try
    
    End Sub 
    
    Shared Sub Serialize(ByVal path As String) 
        Dim emp As New Employee("John", "Peoples")
        emp.id = 3001
        Dim theBoss As New Manager("Michiyo", "Sato")
        theBoss.id = 41
        emp.Boss = theBoss

        Dim ser As New DataContractSerializer(GetType(Employee))
        
        Dim fs As New FileStream(path, FileMode.OpenOrCreate)
        ser.WriteObject(fs, emp)
        fs.Close()
    
    End Sub 
    
    Shared Sub Deserialize(ByVal path As String) 
        Dim ser As New DataContractSerializer(GetType(Employee))
        Dim fs As New FileStream(path, FileMode.Open)
        Dim p As Employee = CType(ser.ReadObject(fs), Employee)
        
        Console.WriteLine("{0} {1}, id:{2}", p.FirstName, p.LastName, p.id)
        fs.Close()
    
    End Sub 
End Class

설명

이 생성자는 클래스의 메서드와 일치하는 메서드 이름을 사용합니다. 메서드는 개체를 IEnumerable<T> Type 반환합니다. 직렬화 또는 역직렬화 중에 컬렉션에 있는 형식을 특성이 적용되는 루트 형식 내에서 사용할 수 있습니다.

적용 대상

KnownTypeAttribute(Type)

지정된 형식을 사용하여 KnownTypeAttribute 클래스의 새 인스턴스를 초기화합니다.

public:
 KnownTypeAttribute(Type ^ type);
public KnownTypeAttribute (Type type);
new System.Runtime.Serialization.KnownTypeAttribute : Type -> System.Runtime.Serialization.KnownTypeAttribute
Public Sub New (type As Type)

매개 변수

type
Type

데이터를 직렬화 또는 역직렬화할 때 알려진 형식으로 포함되는 Type입니다.

예제

다음 예제에서는 명명 Person 된 형식과 역직렬화할 때 포함해야 하는 이름이 지정된 IDInformation 형식을 보여줍니다.

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

적용 대상