如何正确追加StringBuilder?

时间:2016-09-14 12:50:02

标签: c# stringbuilder

以下代码用作十六进制计算器(0-9,A-F)上16位数按钮的通用事件处理程序。

以下说明定义了我需要完成的工作:

如果在按下数字时计算器处于显示模式,该数字将替换显示器的当前内容并将计算器置于输入模式。如果计算器处于输入模式,则有三种情况:

  • 如果显示内容为“0”,则按下的按钮上的数字将替换显示内容。
  • 否则,如果显示内容少于八个字符(因为我们处理的是32位字),按下的按钮上的数字将附加到显示内容中。
  • 否则,按下按钮将被忽略。

我的计算器上的一个按钮将正确更新显示。但是,如果我按下另一个按钮,而不是使用新字符附加StringBuilder,它将显示最后一个按下的按钮的双字符。例如。按一下'C'将显示'C'。按“C”然后说“8”将显示“88”。我的问题在哪里?

    public void ProcessClick(object sender, EventArgs e)
    {
        StringBuilder _button = new StringBuilder();
        _button.Append(((Button)sender).Text);

        if (mode)
        {
            uxDisplay.Text = _button.ToString();
            mode = false;
        }
        else
        {
            if (uxDisplay.Text == "0")
            {
                uxDisplay.Text = _button.ToString();
            }
            else if (uxDisplay.Text.Length < 8)
            {
                uxDisplay.Text = _button.Append(((Button)sender).Text).ToString();
            }
            else
            {
                return;
            }
        }
    }

2 个答案:

答案 0 :(得分:2)

您似乎要追加sender.Text两次的值。

下面:

_button.Append(((Button)sender).Text);

在这里:

uxDisplay.Text = _button.Append(((Button)sender).Text).ToString();

您还要在每次调用Process时创建一个新的StringBuilder,这样您就不会保留最后一个值(除了在uxDisplay控件中)

如此简单的事情:

...
else if (uxDisplay.Text.Length < 8)
{
    uxDisplay.Text += ((Button)sender).Text;
}

你只附加了少量的字符串,所以你不会真正从使用StringBuilder获得那么多的性能(特别是如果你在每次调用时创建一个新的!:P)

答案 1 :(得分:0)

您在创建后直接将按下的按钮文本附加到StringBuilder对象,这就是您获得两倍角色的原因。

你可以选择这样简单的东西:

public void ProcessClick(object sender, EventArgs e)
{
    if (mode)
    {
        uxDisplay.Text = _button.ToString();
        mode = false;
    }
    else
    {
        if (uxDisplay.Text == "0")
        {
            uxDisplay.Text = _button.ToString();
        }
        else if (uxDisplay.Text.Length < 8)
        {
            uxDisplay.Text += ((Button)sender).Text;
        }
        else
        {
            return;
        }
    }
}
相关问题