简体   繁体   中英

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(); 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?)

If I choose public methods instead of the interface.method declaration style, the code compiles:

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

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.

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.

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. Internally the IDisposable.Dispose() method would call your Close method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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