KnownTypeAttribute.MethodName Свойство

Определение

Возвращает имя метода, который возвратит список типов, которые должны распознаваться при сериализации или десериализации.

public:
 property System::String ^ MethodName { System::String ^ get(); };
public string MethodName { get; }
public string? MethodName { get; }
member this.MethodName : string
Public ReadOnly Property MethodName As String

Значение свойства

String

Объект String, содержащий имя метода типа, определяемого классом KnownTypeAttribute.

Примеры

В следующем примере параметр 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

Комментарии

Этот метод должен существовать в классе или структуре, к которым применяется KnownTypeAttribute, должен быть статическим, не должен иметь параметров и должен возвращать экземпляр любого типа, реализующего универсальный интерфейс IEnumerable<T>, например класс Collection<T> или массив объектов Type.

Этот метод вызывается один раз для каждого домена приложения при загрузке контракта данных для типа.

Применяется к