如何通过保留方法名来扩展接口?

Oma*_*mar 3 c# interface

给出两个接口:

interface I1 {
    int Foo();
}

interface I2 {
    void Foo();
}
Run Code Online (Sandbox Code Playgroud)

一节课:

class Test : I1, I2 {
    int I1.Foo() {
        Console.WriteLine("I1.Foo");
        return default(int);
    }

    public void Foo() {
        Console.WriteLine("I2.Foo");
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能扩展接口I2I1通过保持命名的方法Foo

我尝试了以下代码,但它没有编译:

interface I1 {
    int Foo();
}

interface I2 : I1 {
    void I2.Foo();
} 

class Test : I2 { /* same code */ }
Run Code Online (Sandbox Code Playgroud)

drf*_*drf 18

在示例中不清楚I2.Foo()如果允许的话,接口本身将明确声明什么.规范(s.13.4.1)允许实现接口的结构或类声明显式成员实现.(接口不能声明任何实现,显式或其他).

因此,假设我们已经定义:

interface IFoo
{
    void Bar();
}

interface IBaz : IFoo
{
    new void Bar();
}

interface IQux : IBaz { }

class A : IQux // equivalent to class A : IQux, IBaz, IFoo (spec sec. 13.4.6)
{
    void IFoo.Bar()
    {
        Console.WriteLine("IFoo.Bar");
    }

    void IBaz.Bar()
    {
        Console.WriteLine("IBaz.Bar");
    }

    public void Bar()
    {
        Console.WriteLine("A.Bar");
    }

    // Not allowed: void IQux.Bar() {...}
    // Since "The fully-qualified name of the interface member
    // must reference the interface in which the member
    // was declared" (s. 13.4.1)
}
Run Code Online (Sandbox Code Playgroud)

然后,以下驱动程序显示显式接口方法实现的效果.

public static void Main()
{
    A a = new A();
    a.Bar(); // prints A.Bar
    (a as IFoo).Bar(); // prints IFoo.Bar
    (a as IBaz).Bar(); // prints IBaz.Bar
    (a as IQux).Bar(); // prints IBaz.Bar
}
Run Code Online (Sandbox Code Playgroud)

  • 这是迄今为止最完整和最好的答案. (2认同)