2011-06-15 117 views
-1

我一直在读“C#编程语言第4版。”,发现下面的代码示例:继承和方法调用

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(); 

作者指出,调用xF的()之后的在派生方法将被调用,因为

"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()的基地”,所以我不知道我错了。

+0

我想你检查错了。 – jbtule 2011-06-15 15:37:56

+0

我编辑了我的问题以显示我是如何执行检查的。 – Anonymous 2011-06-15 15:50:57

+1

我不知道你在用什么编译器,因为输出“F()in Derived” – jbtule 2011-06-15 16:07:14

回答

0

由于两个基类和派生接口从I.

0

void I<V>.F() {...}该方法可以被称为/触发从“派生”,但是在执行在接口中定义的方法。

void F();