Ufu*_*arı 2 .net c# abstract-class protected
我有一个带有受保护变量的抽象类
abstract class Beverage
{
protected string description;
}
Run Code Online (Sandbox Code Playgroud)
我无法从子类访问它.Intellisense不会显示它可访问.为什么会这样?
class Espresso:Beverage
{
//this.description ??
}
Run Code Online (Sandbox Code Playgroud)
简答: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;
}
}
Run Code Online (Sandbox Code Playgroud)
在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.
}
}
Run Code Online (Sandbox Code Playgroud)