Cannot access protected member in base class [duplicate]

不打扰是莪最后的温柔 提交于 2019-11-29 02:27:55

Why does this happen?

An answer that cannot be argued with is "because the spec says so":

A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type.

But let's explore this restriction behind the scenes.

Explanation

What happens here is the same thing that Eric Lippert describes in the blog post that you linked to. Your code does the equivalent of this:

public abstract class MenuItem
{
    protected string m_Title;
}

public class ContainerItem : MenuItem
{
    void Foo()
    {
        var derivedItem = new ContainerItem();
        derivedItem.m_Title = "test"; // works fine

        var baseItem = (MenuItem)derived;
        baseItem.m_Title = "test"; // compiler error!
    }
}

The problem here stems from the fact that this might happen. For the moment, please disregard the fact that this example uses a method instead of a field -- we 'll come back to it.

public abstract class MenuItem
{
    protected void Foo() {}
}

public class SomeTypeOfItem : MenuItem
{
    protected override void Foo() {}
}

public class ContainerItem : MenuItem
{
    void Bar()
    {
        var baseItem = (MenuItem)something;
        baseItem.Foo(); // #1
    }
}

Look at line #1: how does the compiler know that baseItem is not actually a SomeTypeOfItem? If it is, you certainly must not be able to access Foo! So, as Eric describes, the compiler is unable to statically prove that the access is always legal and because of that it has to disallow this code.

Note that in some cases, for example if

baseItem = (MenuItem)new ContainerItem();

or even

baseItem = (MenuItem)this;

the compiler does have enough information to prove that the access is legal but it still will not allow the code to compile. I imagine that's because the compiler team is not convinced that implementing such special-case handlers is worth the trouble (a point of view which I am sympathetic to).

But... but...

That's all well and good for methods (and properties, which are really methods) -- what about fields? What about this:

public abstract class MenuItem
{
    protected string m_Title;
}

public class SomeTypeOfItem : MenuItem
{
    protected new string m_Title;
}

public class ContainerItem : MenuItem
{
    void Foo()
    {
        var baseItem = (MenuItem)something;
        baseItem.m_Title = "Should I be allowed to change this?"; // #1
    }
}

Since fields cannot be overridden, there should be no ambiguity here and the code should compile and set MenuItem.m_Title irrespective of what the type of something is.

Indeed, I cannot think of a technical reason why the compiler couldn't do this, but there is a good reason in any case: consistency. Eric himself would probably be able to provide a richer explanation.

So what can I do?

How would you access the protected members like m_Title while holding a reference to MenuItem (because of Polymorphism design reasons)?

You simply cannot do that; you would have to make the members internal (or public).

xbonez

protected does mean that the derived class can access it, however, the derived class can access the property of it's own instance. In your example, you can access this.m_Title since that belongs to the instance itself, but you are attempting to access the protected member of another instance (i.e. the instance in the list m_SubMenuItems).

You need getter and setter methods to access it the way you're trying to.

Hopefully this makes it clearer:

class Foo {
    protected int x;

    public void setX(int x) {
        this.x = x;
    }
}

class Bar : Foo {
    Foo myFoo = new Foo();

    public void someMethod() {
        this.x = 5;    // valid. You are accessing your own variable
        myFoo.x = 5;   // invalid. You are attempting to access the protected
                       // property externally
        myFoo.setX(5); // valid. Using a public setter
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!