Why can't I access protected variable in subclass?

我的未来我决定 提交于 2020-01-02 15:59:32

问题


I have an abstract class with a protected variable

abstract class Beverage
{
        protected string description;

}

I can't access it from a subclass. Intellisense doesn't show it accessible. Why is that so?

class Espresso:Beverage
{
    //this.description ??
}

回答1:


Short answer: description is a special type of variable called a "field". You may wish to read up on fields on MSDN.

Long answer: You must access the protected field in a constructor, method, property, etc. of the subclass.

class Subclass
{
    // These are field declarations. You can't say things like 'this.description = "foobar";' here.
    string foo;

    // Here is a method. You can access the protected field inside this method.
    private void DoSomething()
    {
        string bar = description;
    }
}

Inside a class declaration, you declare the members of the class. These may be fields, properties, methods, etc. These are not imperative statements to be executed. Unlike code inside a method, they simply tell the compiler what the members of the class are.

Inside certain class members, such as constructors, methods, and properties, is where you put your imperative code. Here is an example:

class Foo
{
    // Declaring fields. These just define the members of the class.
    string foo;
    int bar;

    // Declaring methods. The method declarations just define the members of the class, and the code inside them is only executed when the method is called.
    private void DoSomething()
    {
        // When you call DoSomething(), this code is executed.
    }
}



回答2:


You can access it from within a method. Try this:

class Espresso : Beverage
{
    public void Test()
    {
        this.description = "sd";
    }
}


来源:https://stackoverflow.com/questions/6717493/why-cant-i-access-protected-variable-in-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!