为什么我不能在子类中访问受保护的变量?

问题描述 投票:2回答:2

我有一个带有受保护变量的抽象类

abstract class Beverage
{
        protected string description;

}

我无法从子类访问它。 Intellisense不会显示它可访问。为什么会这样?

class Espresso:Beverage
{
    //this.description ??
}
c# .net abstract-class protected
2个回答
9
投票

简短回答:description是一种特殊类型的变量,称为“field”。您可能希望阅读字段on MSDN

答案很长:您必须在子类的构造函数,方法,属性等中访问受保护的字段。

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

class声明中,您声明了类的成员。这些可能是字段,属性,方法等。这些不是要执行的命令性语句。与方法中的代码不同,它们只是告诉编译器类的成员是什么。

在某些类成员(例如构造函数,方法和属性)中,您可以放置​​命令式代码。这是一个例子:

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
投票

您可以在方法中访问它。试试这个:

class Espresso : Beverage
{
    public void Test()
    {
        this.description = "sd";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.