加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 19:50:52 所属栏目:百科 来源:网络整理
导读:给出两个接口: 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"); }} 如何通过保持名为Foo的
给出两个接口:

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

如何通过保持名为Foo的方法将接口I2扩展为I1?

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

interface I1 {
    int Foo();
}

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

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

解决方法

在示例中不清楚如果允许的话,在接口本身中明确声明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)
}

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

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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读