比较.ToString()的问题

时间:2014-10-05 20:04:04

标签: c#

所以我制作了一个模拟程序,只是为了更加习惯于c#,并且继承了我所拥有的:

ConsoleKeyInfo Input;
StringBuilder sb = new StringBuilder();
const string Password = "class";

Console.Write("Input Your Password: ");
    do
    {
        Input = Console.ReadKey(true);
        sb.Append(Input.KeyChar); 
    } while (Input.Key != ConsoleKey.Enter);
    Console.WriteLine();

    if (sb.ToString() == Password)
    {
       Console.WriteLine("Correct Password!");
    }
    Console.WriteLine("You Entered: " + sb.ToString());
    Console.WriteLine("The Pass is: " + Password);

    Console.ReadLine();

但是当我来比较sb.ToString()Password时,我的if语句存在问题。虽然如果你把同一个东西放在Password中,那么if语句仍然不会成为现实。

为什么会这样?

1 个答案:

答案 0 :(得分:5)

由于您最后还在Enter添加了StringBuilder密钥,因此您可以在添加之前进行检查:

do
{
    Input = Console.ReadKey(true);
    if(Input.Key != ConsoleKey.Enter)
       sb.Append(Input.KeyChar); 
} while (Input.Key != ConsoleKey.Enter);

或者不是检查它两次,你也可以像这样重构你的循环:

while ((Input = Console.ReadKey(true)).Key != ConsoleKey.Enter)
   sb.Append(Input.KeyChar);