C# 形成未知的 StackOverflowException

C# Forms unknown StackOverflowException

我在代码的最后一行收到最奇怪的 Whosebug 异常:

inputPrice 是一个数字 UpDown

private void inputPreis_ValueChanged(object sender, EventArgs e)
    {
        if (checkBoxUnlock.Checked == false)
        {
            if (oldInputPreisValue == 0)
            {
                inputPreis.Value = 5;
            }

            else if (oldInputPreisValue == 5)
            {
                if (inputPreis.Value > oldInputPreisValue)
                    inputPreis.Value = 8;
                else if (inputPreis.Value < oldInputPreisValue)
                    inputPreis.Value = 5;
            }

            else if (oldInputPreisValue == 8)
            {
                if (inputPreis.Value > oldInputPreisValue)
                    inputPreis.Value = 10;
                else if (inputPreis.Value < oldInputPreisValue)
                    inputPreis.Value = 5;
            }
            //etc...

        }

        oldInputPreisValue = Convert.ToInt32(inputPreis.Value);
    }

该脚本应该让用户将 numericUpDown (inputPrice) 的值更改为固定值。通过勾选checkBoxUnlock复选框,用户可以自由设置值。

这是怎么回事?

我假设当您执行以下操作时:

inputPreis.Value = 5;

然后这将调用 inputPreis_ValueChanged 事件,该事件将再次设置值,然后一次又一次地调用该事件,直到出现 Stack Overflow 异常。

我建议将值存储在本地 属性 中并进行设置,而不是在控件中重置值。