C#为什么从类中调用接口成员会产生错误?

Jac*_*ack 3 c# compiler-construction syntax compiler-errors

所以我有一个界面:

interface IFoo
{
    int Bar();
    int this[int i] {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

还有一个源自它的类

class Foo : IFoo
{
    public int IFoo.Bar()
    {
        //Implementation
    {
    public int IFoo.this[int i]
    {
        //Implementation
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我尝试这样做:

var fooey = new Foo();
int i = Fooey.Bar();
Run Code Online (Sandbox Code Playgroud)

或这个:

int i = Fooey[4];
Run Code Online (Sandbox Code Playgroud)

我希望这些能够正常运作.但是,编译器会生成错误,就好像这些成员不存在一样.这是为什么?我知道我可以演员Foo as IFoo,但我也知道演员表演成本很高,这通常是首先使用界面的原因.

编辑1:这些是生成的错误

'Foo'不包含'Bar'的定义,并且没有扩展方法'Bar'可以找到接受类型'Foo'的第一个参数(你是否缺少using指令或汇编引用?)

"无法将索引应用于'Foo'类型的表达式"

Sea*_*n U 11

您已明确实现 IFoo,这意味着只能通过明确键入的引用来访问其成员IFoo:

// This will work
Foo fooey = new Foo();
int i = ((IFoo)fooey).Bar();
Run Code Online (Sandbox Code Playgroud)

如果您希望成员在不进行强制转换的情况下可见,那么在您的实现中只需单独使用成员名称,而不必使用接口名称作为前缀:

class Foo : IFoo
{
    public int Bar() { /* implementation */ }
    public int this[int i] { /* implementation */ }
}

// now this will also work:
Foo fooey = new Foo();
int i = fooey.Bar();
Run Code Online (Sandbox Code Playgroud)