2016-09-14 88 views
-1

以下代码正在用作十六进制计算器(0-9,A-F)上的16位数字按钮的通用事件处理程序。如何让我的StringBuilder正确追加?

以下说明定义我需要完成的事情:

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

  • 如果显示内容为“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

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

这里:

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

这里:

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

您也从uxDisplay创建每次调用一个新的StringBuilder到过程,因此不坚持的最后一个值(除控制)

如何喜欢简单的东西:

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

您只添加了少量的字符串,因此您不会真正获得使用StringBuilder的所有性能(尤其是在每次调用时创建新的字符串! :P)

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; 
     } 
    } 
}