Mutator使程序无限期运行

时间:2014-11-24 23:30:29

标签: c#

using System;

class mainProgram
{
    static void Main()
    {
        Champions Mundo = new Champions("Mundo", 8000, 0);
        Console.WriteLine(Mundo);   

        //using mutator makes my program run forever at this point
        Mundo.Health = 10000;
        Console.WriteLine(Mundo.Health);

    }

}


class Champions
{
    private string name;
    private int health;
    private int mana;

    public Champions(string name, int health, int mana)
    {
        this.name = name;
        this.health = health;
        this.mana = mana;
    }

    public Champions()
    {
    }

    public int Health
    {
        get
        {
           return this.health;
        }
        set
        {
            this.Health = value;
        }
    }

    public override string ToString()
    {
        return string.Format("Champion: {0} Health: {1} Mana: {2}",
                            this.name, this.health, this.mana); 
    }


 }

大家好,

每当我在我的Main中使用mutator方法时,我的程序将无限期地运行。是什么导致这个问题?是因为我在实例化对象时已经设置了健康值吗? 提前谢谢!

3 个答案:

答案 0 :(得分:2)

您正在调用setter中的setter方法。您应该获得StackOverFlowException,尝试设置支持字段而不是属性本身:

public int Health
{
    get
    {
        return this.health;
    }
    set
    {
        this.health = value;
    }
}

答案 1 :(得分:1)

您的Health属性以递归方式设置自身,因此它将无限重复直到StackOverflowException。您需要设置this.health而不是this.Health

在这种情况下,您还应该使用自动实现的属性,以避免样板代码。而不是

private int health;
public int Health
{
    get { return health; }
    set { health = value; }
}

你可以改为使用

public int Health { get; set; }

将自动为您定义隐藏的私人支持字段。

答案 2 :(得分:0)

除非我弄错了,否则在setter中调用this.Health = value;会再次调用setter(并且一次又一次) - 我会对它进行映像,最终会出现堆栈溢出并死掉......