📜  用于检查指定类的 C# 程序是否为可序列化类(1)

📅  最后修改于: 2023-12-03 14:56:21.570000             🧑  作者: Mango

Introduction to Checking the Serialization of C# Classes

In C#, serialization is the process of converting an object into a format that can be stored or transmitted. This is important for creating applications that save or share data. However, not all classes can be serialized.

To ensure that a C# class can be serialized, you can use the [Serializable] attribute. This attribute allows the class to be serialized and is required for all classes that will be serialized.

To check if a class is serializable, you can use the Type.IsSerializable property. This property returns true if the class is marked as serializable and false if it is not.

using System;

[Serializable]
public class ExampleClass
{
    public int Number { get; set; }
    public string Text { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Type t = typeof(ExampleClass);
        Console.WriteLine(t.IsSerializable);
    }
}

In the example above, ExampleClass is marked with the [Serializable] attribute, so t.IsSerializable returns true.

If you try to serialize a class that is not marked as serializable, you will get a System.Runtime.Serialization.SerializationException.

public class NotSerializableClass
{
    public int Number { get; set; }
    public string Text { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        NotSerializableClass obj = new NotSerializableClass();

        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();

        try
        {
            formatter.Serialize(stream, obj);
        }
        catch (SerializationException e)
        {
            Console.WriteLine("Serialization failed: " + e.Message);
        }
    }
}

In the example above, NotSerializableClass is not marked with the [Serializable] attribute, so attempting to serialize it results in a SerializationException.

By using the [Serializable] attribute and the Type.IsSerializable property, you can easily check if a C# class is serializable.