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

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

概述给出两个接口: interface I1 { int Foo();}interface I2 { void Foo();} 一节课: class Test : I1, I2 { int I1.Foo() { Console.WriteLine("I1.Foo"); return default(int); } pub 给出两个接口:

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}
总结

以上是内存溢出为你收集整理的c# – 如何通过保留方法名来扩展接口?全部内容,希望文章能够帮你解决c# – 如何通过保留方法名来扩展接口?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1225124.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存