开发者

Slightly confused over particulars of explicitly declaring interface with member

开发者 https://www.devze.com 2023-01-22 02:13 出处:网络
I started with this: interface IFoo { string X { get; set; } } class C : IFoo { public void F() { } string IFoo.X { get; set; }

I started with this:

interface IFoo
{
    string X { get; set; }
}

class C : IFoo
{
    public void F()
    {
    }
    string IFoo.X { get; set; }
}

It compiled as I was expecting. No surprise.

Then I go to this:

interface IFoo
{
    string X { get; set; }
}

class C : IFoo
{
    public void F()
    {
        X = "";
    }
    string IFoo.X { get; set; }
}

Now I get 'X is not available in the开发者_如何转开发 current context'.

Wasn't expecting that.

I end up with:

interface IFoo
{
    string X { get; set; }
}

class C : IFoo
{
    public void F()
    {
        X = "";
    }
    private string X;
    string IFoo.X { get; set; }
}

And I never would have thought of that.

Question: The above code in not meshing with my current understanding of thigns because I see two X's. On an intuitive level I can see the compiler doesn't need to get confused. Can someone put it in their words the rules of the language at play here?

Thanks in advance.

Update after answer: I could have casted to the interface as below:

interface IFoo
{
    string X { get; set; }
}

class C : IFoo
{
    public void F()
    {
        (IFoo(this)).X = "";
    }
    string IFoo.X { get; set; }
}


Because you've implemented your interface explicitly (by writing string IFoo.X instead of just string X), you can only access that interface property via the interface.

So you'd need to do

public void F()
{
    ((IFoo)this).X = "";
}

Or not declare the interface explicitly, i.e.

public string X { get; set; }


An explicit interface implementation is not a regular named member of the class, and cannot be accessed by name on the class type (unless you cast it to the interface)

See the spec.


Your explicit implementation of IFoo.X basically limits the use of IFoo.X to cases where the instance of C is treated as an IFoo. If you remove the explicit implementation, you'll get a property X that satisfies the IFoo interface, and can be used when treating the class as a C as well as an IFoo.

0

精彩评论

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

关注公众号