C# 依赖于if语句构造的不同行为

C# 依赖于if语句构造的不同行为,c#,windows-phone-7,if-statement,windows-phone-8,C#,Windows Phone 7,If Statement,Windows Phone 8,我对一小部分代码有点困惑-我创建了自己的解决方案-在键控事件中,我执行一些检查,然后添加一个空格或删除一个字符: 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.

我对一小部分代码有点困惑-我创建了自己的解决方案-在键控事件中,我执行一些检查,然后添加一个空格或删除一个字符:

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语句):


当我有超过10个字符时,代码停止工作,然后尝试删除,我无法删除第10个字符(空格)。

我认为这是因为,通过组合两个if语句,您进入else if,从而添加了一个空格


10-(10/5)%4
等于0,所以请加一个空格。

我必须说,有时我会让自己感到惊讶(有时是坏的一面)——这个问题的答案是显而易见的。我刚刚错过了程序在删除第11个字符后添加第二个空格。事实证明,将问题搁置一段时间可能是一个非常好的主意。谢谢
if (e.Key == System.Windows.Input.Key.Back && text.Length % 5 == 4)
   text = text.Substring(0, text.Length - 1);