如何通过保留方法名称来扩展接口? [英] How to extend an interface by keeping the method names?

查看:117
本文介绍了如何通过保留方法名称来扩展接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于两个接口:

interface I1 {
    int Foo();
}

interface I2 {
    void Foo();
}

和一个类:

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

    public void Foo() {
        Console.WriteLine("I2.Foo");
    }
}



我怎么能扩展接口 I2 I1 通过保持一个名为

How can I extend the interface I2 with I1 by keeping the methods named Foo?

我尝试下面的代码,但它不会编译:

I tried the following code but it doesn't compile:

interface I1 {
    int Foo();
}

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

class Test : I2 { /* same code */ }


推荐答案

有什么显式声明的例子不清楚 I2.Foo()在接口本身将完成,如果它是允许的。该规范(S 13.4.1)允许实现一个接口来声明一个明确的成员实现结构或类。 (接口不能声明,明确或其他任何实现)

It is unclear in the example what explicitly declaring I2.Foo() in the interface itself would accomplish if it were permitted. The specification (s. 13.4.1) allows the struct or class implementing an interface to declare an explicit member implementation. (Interfaces cannot declare any implementation, explicit or otherwise).

因此,假设我们定义:

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

那么下面的驱动程序显示了显式接口方法实现的效果。

Then the following driver shows the effect of the explicit interface method implementation.

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
}

这篇关于如何通过保留方法名称来扩展接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆