不是C#的接口,为什么可以包含字段? [英] Why can't C# interfaces contain fields?
问题描述
例如,假设我想要一个 ICAR
接口,并且所有的实现将包含字段年度
。这是否意味着每一个实现必须单独声明年度
?那岂不是更好只需在接口定义这个?
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.
然后,当你做一个电话:
Then when you do a call:
IFoo ifoo = new Foo();
ifoo.M();
编译器生成code,上面写着问对象什么方法是在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的get和set方法和索引器的设置方法,以及添加和删除事件的方法。但字段是不是方法。有一个领域,你就可以填充与外地位置的引用相关联的槽。因此,接口可以定义方法,属性,索引和事件,但并非领域。
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屋!