序列化继承

序列化继承

问题描述:

如果一些继承自Serializable类,是子类还是序列化?

If something inherits from a Serializable class, is the child class still Serializable?

这要看你的意思是可序列化。如果你指的是CLI标记(即 [Serializable接口] 属性),那么这是的没有的继承(以下证明)。必须明确标明每个派生类 [Serializable接口] 。但是,如果你指的是 ISerializable的接口,然后是:接口实现是继承的,但你必须要小心 - 例如,通过使用虚拟方法,这样派生类可以贡献自己的数据序列化。

It depends what you mean be serializable. If you mean the CLI marker (i.e. the [Serializable] attribute), then this is not inherited (proof below). You must explicitly mark each derived class as [Serializable]. If, however, you mean the ISerializable interface, then yes: interface implementations are inherited, but you need to be careful - for example by using a virtual method so that derived classes can contribute their data to the serialization.

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine(typeof(Foo).IsSerializable); // shows True
        Console.WriteLine(typeof(Bar).IsSerializable); // shows False
    }
}

[Serializable]
class Foo {}

class Bar : Foo {}