为什么 C# 接口不能包含字段? [英] Why can't C# interfaces contain fields?
问题描述
例如,假设我想要一个 ICar
接口,并且所有实现都将包含字段 Year
.这是否意味着每个实现都必须单独声明Year
?简单地在接口中定义这个不是更好吗?
For example, suppose I want an ICar
interface and that all implementations will contain the field Year
. Does this mean that every implementation has to separately declare Year
? Wouldn't it be nicer to simply define this in the interface?
推荐答案
虽然许多其他答案在语义层面是正确的,但我发现从实现细节层面解决这些问题也很有趣.
Though many of the other answers are correct at the semantic level, I find it interesting to also approach these sorts of questions from the implementation details level.
一个接口可以被认为是一个槽的集合,其中包含方法.当一个类实现一个接口时,该类需要告诉运行时如何填充所有必需的槽.当你说
An interface can be thought of as a collection of slots, which contain methods. When a class implements an interface, the class is required to tell the runtime how to fill in all the required slots. When you say
interface IFoo { void M(); }
class Foo : IFoo { public void M() { ... } }
类说当你创建我的一个实例时,在 IFoo.M 的插槽中填充对 Foo.M 的引用.
the class says "when you create an instance of me, stuff a reference to Foo.M in the slot for IFoo.M.
然后当你打电话时:
IFoo ifoo = new Foo();
ifoo.M();
编译器生成的代码表示向对象询问 IFoo.M 的插槽中的方法是什么,然后调用该方法.
the compiler generates code that says "ask the object what method is in the slot for IFoo.M, and call that method.
如果接口是包含方法的槽的集合,那么其中一些槽还可以包含属性的 get 和 set 方法、索引器的 get 和 set 方法以及事件的 add 和 remove 方法.但是字段不是方法.没有与字段关联的槽",然后您可以使用对字段位置的引用来填充".因此,接口可以定义方法、属性、索引器和事件,但不能定义字段.
If an interface is a collection of slots that contain methods, then some of those slots can also contain the get and set methods of a property, the get and set methods of an indexer, and the add and remove methods of an event. But a field is not a method. There's no "slot" associated with a field that you can then "fill in" with a reference to the field location. And therefore, interfaces can define methods, properties, indexers and events, but not fields.
这篇关于为什么 C# 接口不能包含字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!