为什么接口不是 [Serializable]? [英] Why are interfaces not [Serializable]?

查看:31
本文介绍了为什么接口不是 [Serializable]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为将该属性添加到接口将有助于确保您不会创建使用该接口的类并忘记使它们可序列化.

I would think that adding that attribute to an interface would be helpful make sure you do not create classes that use the interface and forget to make them serializable.

这可能是一个非常基本的问题,但我想请教专家.

This could be a very fundamental question, but I wanted to ask the experts.

推荐答案

接口定义了一个契约并且没有自己的任何状态.

Interfaces define a contract and do not have any state of their own.

序列化是关于在对象模型中保存和加载状态.

Serialization is about saving and loading state into and out of an object model.

序列化没有状态的东西没什么意义.

Not much point to serializing something that holds no state.

为了回答强制接口的实现为 Serializable 的实际问题 - 这就是 ISerializable 接口存在.

To answer the practical question of forcing an implementation of an interface to be Serializable - this is why the ISerializable interface exists.

在 .NET 中,您可以声明一个应该实现其他接口的接口:

In .NET you can declare an interface that should implement other interfaces:

interface MustBeSerializable : ISerializable {}

此处查看更多信息.

这篇关于为什么接口不是 [Serializable]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆