仅在继承时更改值

时间:2016-07-28 15:46:27

标签: c#

我目前正在使用C#开发一个非常简单的神奇宝贝应用程序。我不知道如何建立神奇宝贝和他们的战斗类型之间的关系,但我最后做了以下事情:

 abstract class Pokemon
{
    private int number;
    private string name;
    protected string weakness;
    protected string strength;

    public Pokemon(int number, string name)
    {
        this.number = number;
        this.name = name;
        weakness = "none";
        strength = "none";
    }
}

然后我创建了继承Pokemon的单独类来改变类型的特定弱点和强度。

class Fire : Pokemon
{
    public Fire(int number, string name) : base(number, name)
    {
        weakness = "Water";
        strength = "Grass";
    }
}

创建子类的唯一目的是简单地改变父级的一些初始值吗?

从这里开始,我只是打算在为应用程序“创建”神奇宝贝时做以下事情

        pokemon = new Pokemon[6];
        pokemon[0] = new Grass(001, "Bulbasaur");
        pokemon[1] = new Grass(002, "Ivysaur");
        pokemon[2] = new Grass(003, "Venusaur");
        pokemon[3] = new Fire(004, "Charmander");
        pokemon[4] = new Fire(005, "Charmeleon");
        pokemon[5] = new Fire(006, "Charizard");

非常感谢有关如何正确改进应用程序或如何正确使用继承的任何建议:)

1 个答案:

答案 0 :(得分:1)

继承看起来不错,但您可以做一些改进。首先,您不需要为弱点和强度定义受保护的字段,而是使用受保护的属性。其次,使用字符串类型来表示弱点/强度似乎不是最佳选择。我会选择Enum类型。

enum PokemonComponent {
   Water,
   Grass
}

abstract class Pokemon
{
    private int number;
    private string name;
    protected Pokemon(int number, string name)
    {
        this.number = number;
        this.name = name;
    }
    protected abstract PokemonComponent Weakness {
      get;
    }
    protected abstract PokemonComponent Strength {
       get;
    }
}

class Fire : Pokemon
{    
    public Fire(int number, string name) : base(number, name)
    {
    }
    protected override PokemonComponent Weakness {
      get {
         return PokemonComponent.Water;
      }
    }
    protected override PokemonComponent Strength {
      get {
         return PokemonComponent.Grass;
      }
    }
}