类继承不工作的子类?


namespace Littler_story 
{
class Profession
{
public int Strength
{ public get; public set { if ((Strength + value) > Strength) { 
Strength = value; } } }
public int Intelligence
{ public get; public set { if ((Intelligence + value) > 
Intelligence) { Intelligence = value; } } }
public int Agility
{ public get; public set { if ((Agility + value) > Strength) { 
Strength = value; } } }
public int Charisma
{ public get; public set { if ((Charisma + value) > Charisma) { 
Charisma = value; } } }
public int Health
{ public get; public set { if ((Health + value) <= 0) { 
Console.WriteLine("Game over!"); } } }
}
class FireFighter : Profession
{
Strength = 5;
Intelligence = 2;
Agility = 3;
Charisma = 3;
Health = 100;
}

我在消防员类中的所有属性都得到错误。我最初将所有变量定义为每个类中的局部变量。我最近学习了继承,因为我的五个职业类都有相同的属性,我想我可以为它们创建一个超类。正如您所看到的,它们是在Profession中定义的,但是将它们放在我的一个类(消防员)中会导致错误。如果我实现它,这个错误可能会跨越所有的类。我猜这可能是我在职业类中制作自动属性的方式?我得到的错误是,这些属性的力量,敏捷,耐力等不存在于当前的上下文中。

你不能这样设置属性。您需要在构造函数中或通过实例化类然后设置继承的属性来访问它们。

一种方法是:

FireFighter f = new FireFighter ();
f.Strength = 5;

或在构造函数方法中:

public class FireFighter : Profession
{
public FireFighter()
{
Strength = 5;
}
}

最新更新