仅在继承时更改值
本文关键字:继承 | 更新日期: 2023-09-27 17:59:09
我目前正在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";
}
}
然后,我制作了单独的类,继承口袋妖怪,只是为了改变类型的特定弱点和强度。
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");
任何关于如何改进应用程序或如何正确使用继承的建议都将不胜感激:)
继承看起来还可以,但您可以做一些改进。首先,您不需要为弱点和长处定义受保护的字段,而是使用受保护的属性。其次,使用字符串类型表示弱点/强弱似乎不是最好的选择。我会选择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;
}
}
}