1

我正在使用 C# 编写一个简单的游戏来帮助我学习基本的面向对象概念。

在下面的这段代码中:

class entity
    {
    int hp;
    string name;

    public entity()
    {
        hp = 1;
        name = "entity";
    }

    public string status()
    {
        string result;
        result=name + "#" + " HP:" + hp;
        return result;
    }






    class dragon : entity
    {

    new public string name;
    new int hp;


    public dragon()
    {
        hp = 100;
        name = "Dragon";

    }
}

我为“龙”制作了一个对象

dragon mydragon = new dragon();

问题在于以下代码:

mydragon.status();

这将返回一个字符串,但带有实体类对象的“name”和“hp” (即 hp=1,name=entity)。

我想让它返回龙对象的值(hp=100,name=dragon)。我不确定我做错了什么,但看起来很简单。

在摆弄和挣扎了几个小时之后,我能想到的唯一解决方案就是简单地将status()方法复制并粘贴到 dragon 类。但我确信有更好的方法来做到这一点。

提前谢谢了。

4

3 回答 3

6

只需使用访问修饰符装饰字段hpname类。这样,它们也将可供课堂使用,您不必重新定义它们。您可以保持' 的构造函数原样,因为它将在类中的构造函数之后运行,从而覆盖其字段的值。entityprotecteddragondragonentity

它可能如下所示:

public class Entity
{
    protected int hp;
    protected string name;

    public Entity()
    {
        hp = 1;
        name = "entity";
    }

    public override string ToString()
    {
        string result = name + "#" + " HP:" + hp;
        return result;
    }
}

public class Dragon : Entity
{
    public Dragon()
    {
        hp = 100;
        name = "Dragon";
    }
}

C# 中的类名习惯上以大写字母开头。此外,对于返回类的字符串表示之类的东西,ToString()通常会覆盖该方法。

于 2012-07-28T14:35:10.497 回答
0

我会在类中添加virtual关键字到方法和每个继承的类中。entitystatusoverride

编辑:如果您只想使用 Nikola 的代码.ToString()而不是Status()

于 2012-07-28T14:42:45.560 回答
0

进行以下更改...

class entity
    {
    protected int hp;
    protected string name;
...


class dragon : entity
    {

    // new public string name;  - you're creating new variables hiding the base ones
    // new int hp;              - ditto. Don't need them
....
于 2012-07-28T14:43:00.453 回答