2017-03-02 16 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'之一 –