2015-08-21 215 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

我也试试这个,现在我试着输入以前的答案 –