【问题标题】:Inheritance and method invocation through an interface instance通过接口实例进行继承和方法调用
【发布时间】:2011-06-15 15:15:34
【问题描述】:

我一直在阅读《The C# Programming Language. 4th Edition》,发现以下代码示例:

interface I<T>
{
    void F();
}
class Base<U>: I<U>
{
    void I<U>.F() {...}
}
class Derived<U,V>: Base<U>, I<V>
{
void I<V>.F() {...}
}
...
I<int> x = new Derived<int,int>();
x.F();

作者声明在调用 x.F() 后会调用 Derived 中的方法,因为

"Derived<int,int> effectively reimplements I<int>"

我用 C# 4.0 编译器检查过,发现这个语句实际上调用了 Base 中的方法。你能解释一下这种行为吗?

提前致谢。

编辑:这是用于检查的工作代码:

using System;

interface I<T>
{
    void F();
}

class Base<U>: I<U>
{
    void I<U>.F()
    {
        Console.WriteLine("F() in Base");
    }
}

class Derived<U,V>: Base<U>, I<V>
{
    void I<V>.F()
    {
        Console.WriteLine("F() in Derived");
    }
}

public class MainClass
{
    public static void Main()
    {
        I<int> x = new Derived<int,int>();
        x.F();
    }
}

它输出“F() in Base”,所以我不知道我哪里错了。

【问题讨论】:

  • 我已经编辑了我的问题以显示我是如何执行检查的。
  • 我不知道您使用的是什么编译器,因为它会输出“F() in Derived”

标签: c#-4.0


【解决方案1】:

因为来自 I 的 Base 和 Derived 接口。

【讨论】:

    【解决方案2】:

    void I&lt;V&gt;.F() {...} 该方法可能被“派生”调用/触发,但正在执行接口中定义的方法。

    void F();

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2018-05-10
      相关资源
      最近更新 更多