Поделиться через


Type.IsSerializable Свойство

Определение

Внимание

Formatter-based serialization is obsolete and should not be used.

Возвращает значение, указывающее, является ли Type двоичный сериализуемый.

public:
 virtual property bool IsSerializable { bool get(); };
public:
 property bool IsSerializable { bool get(); };
[System.Obsolete("Formatter-based serialization is obsolete and should not be used.", DiagnosticId="SYSLIB0050", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public virtual bool IsSerializable { get; }
public virtual bool IsSerializable { get; }
public bool IsSerializable { get; }
[<System.Obsolete("Formatter-based serialization is obsolete and should not be used.", DiagnosticId="SYSLIB0050", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
member this.IsSerializable : bool
member this.IsSerializable : bool
Public Overridable ReadOnly Property IsSerializable As Boolean
Public ReadOnly Property IsSerializable As Boolean

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

Значение />, если двоичный сериализуемый; в противном случае .

Реализации

Атрибуты

Примеры

В следующем примере создается экземпляр MyTestClass класса, задает атрибут [Serializable] и проверяется IsSerializable свойство для true или false.

using System;
namespace SystemType
{
    public class MyClass
    {
        // Declare a public class with the [Serializable] attribute.
        [Serializable] public class MyTestClass
        {
        }
        public static void Main(string []args)
        {
            try
            {
                bool myBool = false;
                MyTestClass myTestClassInstance = new MyTestClass();
                // Get the type of myTestClassInstance.
                Type myType = myTestClassInstance.GetType();
                // Get the IsSerializable property of myTestClassInstance.
                myBool = myType.IsSerializable;
                Console.WriteLine("\nIs {0} serializable? {1}.", myType.FullName, myBool.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("\nAn exception occurred: {0}", e.Message);
            }
        }
    }
}
open System

// Declare a public class with the [Serializable] attribute.
[<Serializable>]
type MyTestClass() = class end

try
    let myTestClassInstance = MyTestClass()
    // Get the type of myTestClassInstance.
    let myType = myTestClassInstance.GetType()
    // Get the IsSerializable property of myTestClassInstance.
    let myBool = myType.IsSerializable
    printfn $"\nIs {myType.FullName} serializable? {myBool}."
with e ->
    printfn $"\nAn exception occurred: {e.Message}"
Namespace SystemType
    Public Class [MyClass]
        ' Declare a public class with the [Serializable] attribute.
        <Serializable()> Public Class MyTestClass
        End Class
        Public Overloads Shared Sub Main()
            Try
                Dim myBool As Boolean = False
                Dim myTestClassInstance As New MyTestClass()
                ' Get the type of myTestClassInstance.
                Dim myType As Type = myTestClassInstance.GetType()
                ' Get the IsSerializable property of myTestClassInstance.
                myBool = myType.IsSerializable
                Console.WriteLine(ControlChars.Cr + "Is {0} serializable? {1}.", myType.FullName, myBool.ToString())
            Catch e As Exception
                Console.WriteLine(ControlChars.Cr + "An exception occurred: {0}", e.Message.ToString())
            End Try
        End Sub
    End Class
End Namespace 'SystemType

Комментарии

Типы, определенные в .NET Standard, не помечены.SerializableAttribute Вместо этого каждая реализация .NET определяет, является ли тип двоичным сериализуемым. Во время выполнения свойство можно использовать IsSerializable для определения того, поддерживает ли эта реализация двоичную сериализацию экземпляра типа. Дополнительные сведения и пример см. в разделе "Как определить, является ли сериализуемый объект .NET Standard".

Если текущий Type представляет созданный универсальный тип, это свойство применяется к определению универсального типа, из которого был создан тип. Например, если текущий Type представляет MyGenericType<int> (MyGenericType(Of Integer) в Visual Basic), значение этого свойства определяется MyGenericType<T>.

Если текущий Type представляет параметр типа в определении универсального типа или универсального метода, это свойство всегда возвращается false.

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

См. также раздел