gpt4 book ai didi

c# - .NET C# 在父接口(interface)中显式实现祖 parent 的接口(interface)方法

转载 作者:太空狗 更新时间:2023-10-29 21:19:51 24 4
gpt4 key购买 nike

这个标题很啰嗦,不是吗?...

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

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 */

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

如果不是,为什么?

最佳答案

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

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

关于c# - .NET C# 在父接口(interface)中显式实现祖 parent 的接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4501394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com