开发者

Unexpected c# interface implementation compiler error

开发者 https://www.devze.com 2023-01-16 16:24 出处:网络
I just came across this weird behavior today: interface IFooBar { void Foo(); void Bar(); } class FooBar : IFooBar

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 yo开发者_C百科u 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


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消