2017-03-02 85 views
0

我在循环“while”的公共静态方法中编写了一些代码。但是这个循环在“if”语句之后结束,并且应用程序不会抛出任何异常。这里是代码:while ...循环在if语句公用静态方法后结束C#

public static void ShortcutDetect() 
{ 
    ShortkeyIndex = 0; 
    while(ShortkeyIndex < 1000) 
    { 
     File.WriteAllText(@"C:\Users\OEM\Desktop\log.txt", 
      File.ReadAllText(@"C:\Users\OEM\Desktop\log.txt") + Convert.ToString(ShortkeyIndex)); 
     if(Program.key.Replace("LShiftKey","Shift") 
      .Replace("RShiftKey","Shift").Replace("RMenu","Alt") 
      .Replace("LMenu","Alt").Replace("RControlKey","Ctrl") 
      .Replace("LControlKey","Ctrl").EndsWith(RawShortkeys[ShortkeyIndex])) 
     { 
      MessageBox.Show(RawShortkeys[ShortkeyIndex]); 
     } 
     ShortkeyIndex++; 
    } 
} 

事先感谢。

+1

为什么would'n什么时候结束? 1000次迭代需要很短的时间。 – Guy

+2

您如何得出“如果”声明“之后此循环结束”的结论?你是如何测试它的? –

+0

你确定只有一个“循环”被执行?你调试了代码吗?从你发布的内容来看,没有迹象表明这一点。 – HimBromBeere

回答

0

我们只是实现它的权利:

public static void ShortcutDetect() { 
    // Take loop independent code out of the loop: 
    // and, please, format it out: 
    var source = Program.key 
    .Replace("LShiftKey", "Shift") 
    .Replace("RShiftKey", "Shift") 
    .Replace("RMenu", "Alt") 
    .Replace("LMenu", "Alt") 
    .Replace("RControlKey", "Ctrl") 
    .Replace("LControlKey", "Ctrl"); 

    // Wrong type of loop (while): what is ShortkeyIndex? 
    // where has it been declared, why 1000? 
    // Please, have a look how the right loop easy to implement and read 
    foreach (var item in RawShortkeys) { 
    // Debug: let's output item onto Console 
    // Console.WriteLine(item); 
    // Debug: ...or in the file 
    // File.AppendAllText()@"C:\Users\OEM\Desktop\log.txt", " " + item); 

    if (source.EndsWith(item)) // <- put a break point here, inspect item's 
     MessageBox.Show(item); 
    } 
} 
+0

谢谢你的帮助。如果此方法检查RawShortkeys [ShortkeyIndex],我发现我的应用程序停在.EndsWith()处。 – SOCIOPATH

+1

@SOCIOPATH:你在当前循环中遇到了几个问题:完全不清楚'ShortkeyIndex'是什么以及它声明的位置;什么是'1000'(幻数)如何与'RawShortkeys'集合相关联;为什么'while'循环,当你真的想'foreach'之一 –