2015-08-21 312 views
2

我試圖在這裏實現的是,當您按下「1」時,它會將其與「code_1」進行覈對,然後如果匹配,則會顯示「key1 correct」,然後檢查其他代碼。但是編譯器說無法將system.consolekeyinfo轉換爲字符串

不能system.consolekeyinfo轉換爲字符串

所以我不知道我該怎麼解決這個問題。下面是我使用的代碼:

static void Main(string[] args) 
    { 
     string first_time = null; 
     string paktc = "Press any key to continue . . .\r\n"; 
     string code_1 = "1"; 
     string code_2 = "2"; 
     string code_3 = "3"; 
     string code_4 = "4"; 
     if (first_time == null) 
     { 
      Console.WriteLine("\r\nYour code is 1234\r\n"); 
      Console.WriteLine(paktc); 
      Console.ReadKey(); 
      Console.WriteLine("Insert Code Now\r\n"); 

      ConsoleKeyInfo key1 = Console.ReadKey(); 
      if (code_1 = key1) 
      { 
       ConsoleKeyInfo key2 = Console.ReadKey(); 
       if (code_2 = key2) 
       { 
        ConsoleKeyInfo key3 = Console.ReadKey(); 
        if (code_3 = key3) 
        { 
         Console.WriteLine("Key3 Correct\r\n"); 
         ConsoleKeyInfo key4 = Console.ReadKey(); 
         if (code_4 = key4) 
         { 
          Console.WriteLine("Key4 Correct\r\n"); 
          Console.ReadKey(); 
          Console.WriteLine(paktc); 
         } 
         else 
         { 

         } 
        } 
        else 
        { 

        } 
       } 
       else 
       { 

       } 
      } 
      else 
      { 

      } 
     } 
    } 
} 
+0

添加否則效率不高。你以前是否用Switch語句編寫代碼? – Muks

回答

1

目前你所得到的錯誤是因爲你忘了:

=和==是不一樣的事情。第一是作業,第二是比較。

而且你不能沒有if語句指定stringConsoleKeyInfo,反之亦然,並絕對。但是,即使您已經修復了此問題,仍然無法將stringConsoleKeyInfo進行比較。你可以得到它的KeyChar財產和比較,爲一個char雖然:

if (keyInfo.KeyChar == myString[0]) 

是有效的(如string可以被索引,以獲取其char S)。你的情況,你可以只使用一個字符,並使其更簡單:

if (keyInfo.KeyChar == '1') 
+0

噢,感謝那 –

0

使用Console.Read();相反,它返回一個INT女巫可以被類型強制轉換成字符。還代替具有4個字符串與他們的一個字符,則可以有一個串在它的完整代碼,並用它作爲一個數組,參見下面

static void Main(string[] args) 
    { 
     string pw = "123"; 
     Console.WriteLine("Enter the first digit of the password"); 
     char toTest = (char) Console.Read(); 
     Console.Read(); 
     Console.Read(); 
     if (toTest == pw[0]) 
     { 
      Console.WriteLine("Enter the second digit of the password"); 
      toTest = (char)Console.Read(); 
      Console.Read(); 
      Console.Read(); 
      if (toTest == pw[1]) 
      { 
       Console.WriteLine("Enter the third digit of the password"); 
       toTest = (char)Console.Read(); 
       Console.Read(); 
       Console.Read(); 
      } 
     } 
    } 

額外Console.Read()的示例;命令是捕捉按下輸入時輸入的不可見字符。

+0

如果你在這篇文章中解釋了問題的根源(就像我在其他答案中評論的那樣),那將會很好。另外,如果你要解決所有這些問題,你還可以寫一個'for'循環。 – BradleyDotNET

+0

我也試試這個,現在我試着輸入以前的答案 –