为什么我不能访问子类中受保护的变量? [英] Why can't I access protected variable in subclass?

查看:132
本文介绍了为什么我不能访问子类中受保护的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 抽象类饮料
{
        保护字符串描述;

}
 

我无法从一个子类访问它。智能感知不显示它访问。为什么会这样?

 类居preSSO:饮料
{
    //this.description?
}
 

解决方案

的回答:说明是可变的一种特殊类型被称为的字段。你不妨读一下场在MSDN

简短的回答:你必须访问一个构造函数,方法,属性等子类的保护领域

 类的子类
{
    //这些字段声明。你不能说这样的话'this.description =foobar的;这里。
    字符串FOO;

    //这里是一个方法。您可以访问此方法中受保护的领域。
    私人无效DoSomething的()
    {
        串吧=说明;
    }
}
 

略更详细的回答:

的声明,声明中的成员的类的的。这些可能是字段,属性,方法等,这是不被执行的code。不同的方法在code,它只是告诉编译器什么类的成员。

在一定的阶级成员,如构造函数,方法和属性,是你把你的当务之急code。下面是一个例子:

 类Foo
{
    //声明领域。这些只是定义在类的成员。
    字符串FOO;
    INT吧;

    //声明的方法。该方法的声明只是定义类的成员,而且仅执行内部它们code当方法被调用。
    私人无效DoSomething的()
    {
        //当你调用DoSomething的(),则执行该code。
    }
}
 

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

解决方案

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

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

Slightly more detailed answer:

Inside a class declaration, you declare the members of the class. These may be fields, properties, methods, etc. This is not code that is executed. Unlike code inside a method, it simply tells 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.
    }
}

这篇关于为什么我不能访问子类中受保护的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆