c# - 接口(interface)继承多个接口(interface) : how is this handled by a C# compiler?

标签 c# .net interface mono

最近我发现 C# 允许

An interface can inherit from one or more base interfaces.

例如,Caliburn.Micro 中的 IScreenhttp://caliburnmicro.codeplex.com/SourceControl/latest#src/Caliburn.Micro/IScreen.cs 中执行此操作

namespace Caliburn.Micro
{
    public interface IScreen : IHaveDisplayName, IActivate, IDeactivate, 
        IGuardClose, INotifyPropertyChangedEx
    {
    }
}

我明白为什么这是有用的,因为它意味着实现 IScreen 的类还需要实现其他接口(interface)。

但我想知道 C# 如何明智地处理该编译器和运行时。

这个问题的一些背景/背景:

我的背景是接口(interface)定义方法表,实现接口(interface)的类有自己的方法表,以及指向它们实现的接口(interface)的方法表的指针。

在我脑海中盘旋的子问题源于我过去与人们进行的各种多类继承讨论,我认为它们也适用于这种情况:

  • 如果一个接口(interface)能够从多个基接口(interface)继承,该表中方法的顺序将如何?
  • 如果这些接口(interface)有共同的祖先怎么办:这些方法会在表中出现多次吗?
  • 如果这些接口(interface)有不同的祖先,但方法名称相似怎么办?

(我在这里使用方法一词,暗示在接口(interface)中定义的属性将具有 get_ 或 set_ 方法)。

非常感谢任何对此的见解,以及关于如何更好地表达这个问题的提示。

最佳答案

首先,让我们明确地说“接口(interface)继承”与基于类的继承并不完全相同(并且对两者都使用“继承”一词可能会产生误导)。

这是因为接口(interface)不能自己实例化,所以编译器/运行时对不必跟踪如何对独立接口(interface)类型进行虚拟调用(例如,您不需要知道如何调用 IEnumerable.GetEnumerator -- 您只需要知道如何在特定类型的对象上调用它)。这允许在编译时以不同的方式处理事情。

现在我实际上不知道编译器是如何实现“接口(interface)继承”的,但它是如何实现的:

Having an interface be able to inherit from multiple base interfaces, how would the order of methods in that table be?

“派生”接口(interface)没有必要有一个方法表,其中包含来自其所有祖先接口(interface)的方法,因为它实际上并不实现其中任何一个。对于每个接口(interface)类型来说,只有一个它自己定义的方法表就足够了。

What if those interfaces have common ancestors: would those methods appear multiple times in the table?

鉴于上一个问题的答案,否。最后,具体类型只会实现 IFoo 一次,而不管 IFoo 在已实现接口(interface)的“层次结构”中出现了多少次。 IFoo 中定义的方法只会出现在IFoo 的簿记表中。

What if those interfaces have different ancestors, but similar method names?

同样,没问题。您需要适当的语法来告诉编译器“这里是如何实现 IFoo.Frob,这里是 IBar.Frob”,但是由于 IFooIBar 将映射到单独的表中,没有技术问题。

当然,这留下了“如何在运行时分派(dispatch)方法?”的问题。未回答。但是不难想象一个可能的解决方案:每个具体类型 C 都有指向它实现的每个接口(interface)的一个方法表的指针。当需要进行虚拟方法调用时,运行时会查看具体类型,找到要调用其方法的接口(interface)表(接口(interface)类型是静态已知的)并进行调用。

关于c# - 接口(interface)继承多个接口(interface) : how is this handled by a C# compiler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19974832/

相关文章:

.net - SSL 256 位加密 - Azure 网站上

java - 接口(interface)内 transient

c++ - 接口(interface)的延迟实现

C# 接口(interface)与类访问

c# - 当应用程序在 UWP 中更新时运行一些代码

c# - 如何在我的应用程序中调用功能的窗口中创建键盘快捷方式?

c# - 使用反射获取通用列表始终为空

c# - tablelayoutpanel 单元格未在 c# win 窗体中均匀填充

c# - 使用Task.WhenAny等待几种不同的异步操作的结果

java - 自定义泛型解释