-3

我有以下内容。

只有当变量在构造函数中时,编译器才会识别派生类中的变量 flyBehaviour。这是为什么?

abstract class Duck
{
    protected IFlyBehaviour flyBehaviour;

    public IFlyBehaviour FlyBehaviour
    {
        get
        {return flyBehaviour;}
        set
        {flyBehaviour=value;}
    }

}

class MullardDuck: Duck
{
    flyBehaviour  //the compiler doesn't recognize this variable here
    public MullardDuck()
    {
        flyBehaviour = new FlyWithWings(); //here the compiler recognize this variable
    }
}
4

3 回答 3

1

这只是一个语法错误,而不是由于继承。

你也不能这样写:

abstract class Duck
{
    protected IFlyBehaviour flyBehaviour;
    flyBehaviour = ... ; // This wouldn't compile.

    public IFlyBehaviour FlyBehaviour
    {
        get
        {return flyBehaviour;}
        set
        {flyBehaviour=value;}
    }
}

通过调用flyBehaviour,您可以调用已定义但在基类中的受保护字段。

如果要初始化该字段,则必须在构造函数中进行,如您所想,或者您可以在任何方法或属性中操作值。

class MullardDuck: Duck
{
    public MullardDuck()
    {
        // You can access the field from the constructor
        this.flyBehaviour = new FlyWithWings();
    }

    public void Method(){
        // You can also access the field from a method
        this.flyBehaviour = new FlyWithWings();
    }
}
于 2012-10-07T13:42:03.437 回答
0

why do you need to use that var in that place? can't you only do something like this if you say that in this place the var is recognized?

class MullardDuck: Duck
{
    IFlyBehaviour mullardFlyBehaviour;
    public MullardDuck(){
        mullardFlyBehaviour = flyBehaviour;
    }
}
于 2012-10-07T13:38:01.193 回答
0

You can access the variable in a method of derived class. Try to access the variable in the MullarDuck() function (constructor) or any other function you might define in the derived class. As per definition, the derived class already have this variable so you don't have to access that variable outside any method or property.

If you want to assign any value to this variable, you will have to assign it either in a method or in a property.

于 2012-10-07T13:38:19.770 回答