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

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

abstract class Beverage { protected string description; } 

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

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

简短回答: description是一种称为“ 字段 ”的特殊变量。 您可能希望阅读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. } } 

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

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