开发者

Inheritance and method invocation through an interface instance

I've been reading "The C# Programming Language. 4th Edition" and found the following code sample:

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 Deri开发者_StackOverflow社区ved<int,int>();
x.F();

Authors state that after calling x.F() the method in Derived will be invoked, because

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

I've checked with C# 4.0 compiler and found that this statement actually invokes the method in Base. Can you explain such behaviour?

Thanks in advance.

edit: here is the working code used for check:

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

It outputs "F() in Base", so I don't know where I am wrong.


Because both Base and Derived interface from I.


void I<V>.F() {...} The method may be called/triggered from "Derived" but is executing the method defined in the interface.

void F();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜