class、结构或接口成员声明中的意外符号“=”

Unexpected symbol `=' in class, struct, or interface member declaration

我收到以下代码的上述错误:

public class Sheep : Animal {
    //hpMax = 100;
    //power = 10;
    //defense = 10;
    //speed = 10;
    animalName = "Sheep Test";

    public override void Attack()
    {
        Debug.Log(animalName);
    }

}

看来我无法在方法之外分配变量。是这样吗?这意味着我必须创建一个 "AssignStats()" 方法来分配 HPMax、功率、防御、速度等。我想这可能很清楚为什么我想避免在每次调用时将这个添加的步骤添加到代码中动物对象。

还是我遗漏了一些明显的东西?

您缺少 animalName 属性的类型声明。

如果在基 class 中将 animalName 声明为受保护变量,您可以在构造函数中设置 animalName,如下所示:

public Sheep() : base(){
   animalName = "Sheep Test";
}

这假设 Animal class 的定义类似于:

public class Animal{
   protected string animalName;  //protected allows descendent classes 
                                 //direct access to the var.
}