千万接口派生自System.Object? C#规范说是的,埃里克说不准,现实说不是的、说不、说不准、接口

2023-09-02 01:39:41 作者:总有一天,你的心上人,会身披土豆饼,脚踩棉花糖,手持烤肉鸡腿

问题很简单,问的称号。

C#4.0规范说:(§4.2.2)

  

的对象类的类型是最终的   基类中的所有其它类型的。所有的   在C#类型直接或间接地   源自对象类类型。

Eric利珀特说:

  

接口类型,不是班,   不是来自对象。

现实说:

 键入T = typeof运算(ICloneable).BaseType;
Console.WriteLine(T == NULL);
 

  

那么,规格不对还是什么?谁相信?

解决方案

这不是很简单的一个,你可能会想一个问题:)

接口不的导出的距离对象但你可以叫对象的成员他们。所以,你可以叫的ToString()在一个前pression具有的IDisposable 的编译时类型,例如,

巧的是,我的开销尼尔Gafter和埃里克之间的对话,在NDC讨论正是这一点......

我相信规范的4.2.2节已经过去简单的,很遗憾。希望的Mads和Eric将修复它在将来的版本 - 我会寄给他们,以确保他们看到了这个问题。

我也在努力寻找在规范来支持这个答案了剩下的东西。 C#的4规范第3.4.5来亲如我能找到的:

  

接口的成员是在接口中和该接口的所有基接口声明的成员。类对象成员都没有,严格地说,任何接口(13.2)的成员。然而,在类中的成员对象可通过成员查找任何接口类型(7.4)。

从接口类型为对象转换覆盖6.1.6:

  

隐式引用转换为:

        从任何的引用类型的到对象动态。   

Question is simple and asked in the title.

C 中Typeof是干什么的

C# 4.0 Specification says: (§4.2.2)

The object class type is the ultimate base class of all other types. Every type in C# directly or indirectly derives from the object class type.

Eric Lippert says:

Interface types, not being classes, are not derived from object.

Reality says:

Type t = typeof(ICloneable).BaseType;
Console.WriteLine(t == null);

True

So is spec wrong or what? Whom to believe?

解决方案

It's not quite as simple a question as you might think :)

Interfaces don't derive from object but you can call the members of object on them. So you can call ToString() on an expression which has a compile-time type of IDisposable, for example.

Coincidentally, I overhead a conversation between Neal Gafter and Eric at NDC discussing exactly this point...

I believe section 4.2.2 of the spec is over simplified, unfortunately. Hopefully Mads and Eric will fix it up for a future release - I'll mail them to make sure they see this question.

I'm also struggling to find anything in the spec to back up the rest of this answer. Section 3.4.5 of the C# 4 spec comes as close as I can find:

The members of an interface are the members declared in the interface and in all base interfaces of the interface. The members in class object are not, strictly speaking, members of any interface (13.2). However, the members in class object are available via member lookup in any interface type (7.4).

The conversion from an interface type to object is covered by section 6.1.6:

The implicit reference conversions are:

From any reference-type to object and dynamic.