Why can't I access protected variable in subclass?

你说的曾经没有我的故事 提交于 2019-12-06 11:15:27

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.
    }
}

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

class Espresso : Beverage
{
    public void Test()
    {
        this.description = "sd";
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!