C# 可序列化的继承

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/182873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:56:22  来源:igfitidea点击:

Serializable Inheritance

c#.netvb.net

提问by Joe Morgan

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

如果某些东西继承自 Serializable 类,那么子类是否仍然是 Serializable?

采纳答案by Marc Gravell

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

这取决于您的意思是可序列化。如果您指的是 CLI 标记(即[Serializable]属性),那么这不是继承的(证明如下)。您必须将每个派生类显式标记为[Serializable]. 但是,如果您指的是ISerializable接口,那么是的:接口实现是继承的,但您需要小心 - 例如,通过使用一种virtual方法,以便派生类可以将其数据贡献给序列化。

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 {}