2014-03-03 34 views
0

我有點困惑與一小部分的代碼 - 我創建了我自己的解決方案the problem asked here - 在KeyUp事件我執行一些檢查,然後添加一個空格或刪除一個字符:不同的行爲依賴於如果語句構造

private void myTextbox_KeyUp1(object sender, System.Windows.Input.KeyEventArgs e) 
{ 
    string text = myTextbox.Text; 
    if (text.Length > 3) 
    { 
     if (e.Key == System.Windows.Input.Key.Back) 
     { 
     if (text.Length % 5 == 4) text = text.Substring(0, text.Length - 1); 
     } 
     else if ((text.Length - (text.Length/5)) % 4 == 0) text += " "; 
    } 
    myTextbox.Text = text; 
    myTextbox.SelectionStart = text.Length; 
} 

該代碼工作得很好。但是,如果我只是改變了內部if語句是這樣的(合併兩個if語句):

if (e.Key == System.Windows.Input.Key.Back && text.Length % 5 == 4) 
    text = text.Substring(0, text.Length - 1); 

代碼停止工作時,我有超過10個字符,然後嘗試刪除,我不能夠刪除第十個字符(空格)。

回答

1

我想這是因爲,通過if語句,你走進否則,如果結合2,從而增加了空間

10 - (10/5) % 4不等於0,所以添加一個空格。

+0

我必須說有時候我會讓自己感到驚訝(有時還會從不好的一面) - 這個問題的答案很明顯。我錯過了該程序在刪除第11個字符後添加了第二個空格。事實證明,將問題擱置一段時間可能是一個非常好的主意。謝謝。 – Romasz