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

.NET C#在父接口中显式实现祖父母的接口方法

发布时间:2020-12-15 08:23:28 所属栏目:百科 来源:网络整理
导读:那个头衔是满口的,不是吗?…… 这是我正在尝试做的事情: public interface IBar { void Bar();}public interface IFoo: IBar { void Foo();}public class FooImpl: IFoo { void IFoo.Foo() { /* works as expected */ } //void IFoo.Bar() { /* i'd like t
那个头衔是满口的,不是吗?……

这是我正在尝试做的事情:

public interface IBar {
     void Bar();
}
public interface IFoo: IBar {
    void Foo();
}
public class FooImpl: IFoo {
    void IFoo.Foo()   { /* works as expected */ }
    //void IFoo.Bar() { /* i'd like to do this,but it doesn't compile */ }

    //so I'm forced to use this instead:
    void IBar.Bar()   { /* this would compile */ }
}

我的问题是,调用Bar()是不方便的:

IFoo myFoo = new FooImpl();
//myFoo.Bar(); /* doesn't compile */
((IBar)myFoo).Bar(); /* works,but it's not necessarily obvious 
                        that FooImpl is also an IBar */

那么…有没有办法在我的类中声明IFoo.Bar(){…},除了基本上将两个接口合并为一个?

如果没有,为什么?

解决方法

可以在接口中使用new关键字来显式隐藏它扩展的接口中声明的成员:
public interface IBar
{
    void Bar();
}

public interface IFoo:IBar
{
    void Foo();
    new void Bar();
}

public class Class1 : IFoo
{
    void Bar(){}

    void IFoo.Foo(){}

    void IFoo.Bar(){}

    void IBar.Bar(){}
}

(编辑:李大同)

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

    推荐文章
      热点阅读