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
Serializable Inheritance
提问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 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.
这取决于您的意思是可序列化。如果您指的是 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 {}