简体   繁体   English

意外的C#接口实现编译器错误

[英]Unexpected c# interface implementation compiler error

I just came across this weird behavior today: 我今天才遇到这种奇怪的行为:

interface IFooBar
{
    void Foo();
    void Bar();
}

class FooBar : IFooBar
{
    void IFooBar.Foo()
    {
    }

    void IFooBar.Bar()
    {
        this.Foo();
    }
}

The line this.Foo(); 这行this.Foo(); raises the compiler error 引发编译器错误

'MyProject.FooBar' does not contain a definition for 'Foo' and no extension method 'Foo' accepting a first argument of type 'MyProject.FooBar' could be found (are you missing a using directive or an assembly reference?) 'MyProject.FooBar'不包含'Foo'的定义,并且找不到扩展方法'Foo'接受类型为'MyProject.FooBar'的第一个参数(您是否缺少using指令或程序集引用?)

If I choose public methods instead of the interface.method declaration style, the code compiles: 如果我选择公共方法而不是interface.method声明样式,则代码将编译:

class FooBarOk : IFooBar
{
    public void Foo()
    {
    }

    public void Bar()
    {
        this.Foo();
    }
}

I'd like to understand why this error is raised, and how it can be worked around using the interface.method notation 我想了解为什么会出现此错误,以及如何使用interface.method表示法解决该错误。

Have you tried using the interface syntax in code? 您是否尝试过在代码中使用接口语法?

((IFooBar)this).Foo ();

I expect it's because the implementation is effectively hidden, ensuring that you must cast it to an IFooBar in order to use it. 我希望这是因为实现实际上是隐藏的,确保您必须将其IFooBar转换为IFooBar才能使用。

To work around it, you can write: 要变通解决,您可以编写:

((IFooBar)this).Foo();

Take a look at the Explicit Interface Implementation Tutorial for answer why this.Foo() doesn't work. 查看Explicit Interface Implementation Tutorial,以回答为什么this.Foo()不起作用。

This is called explicit interface implementation. 这称为显式接口实现。 It lets you implement an interface without exposing those methods publicly. 它使您可以实现接口,而无需公开公开这些方法。 For example you could implement IDisposable but provide a public Close() method which may make more sense to the users of your api. 例如,您可以实现IDisposable,但提供一个公共Close()方法,这对于您的api用户可能更有意义。 Internally the IDisposable.Dispose() method would call your Close method. 在内部,IDisposable.Dispose()方法将调用您的Close方法。

interface IFooBar
{
    void Foo();
    void Bar();
}

class FooBar : IFooBar
{
    void IFooBar.Foo()
    {
    }

    void IFooBar.Bar()
    {
        ((IFooBar)this).Foo();
    }
}

is a way for you to call the Foo method 是您调用Foo方法的一种方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM