C# Conversion of ReadKey() to int



我是C#的新手,并被告知要创建一个基于文本的口袋妖怪战斗模拟器,因此在下面的代码中,我有一种获得用户输入的方法,并确定口袋妖怪的性质获取:

public static void NatureSelection(out int statIndex1, out int statIndex2)
    {
        Console.WriteLine("If you wish to have a neutral nature, Enter 0 in the next line, If not, enter any key to continue");
        char holder = Convert.ToChar(Console.ReadKey());
        statIndex1 = Convert.ToInt16(holder);
        if (statIndex1 == 0) 
        {
            statIndex2 = 0;
        }
        Console.WriteLine("Please Select A Nature For Your Pokemon By Entering The Number Beside The Stats That You Want To Increase ");
        statIndex1 = Convert.ToInt16(Console.ReadKey());
        while (!(statIndex1 > 0 && statIndex1 <=5))
        {
            statIndex1 = Convert.ToInt32(Console.ReadKey());
            Console.WriteLine("Invalid Value,Please Try Again");
        }

        Console.WriteLine("Now Enter The Number Beside The Stats That You Want To Decrease ");
        statIndex2 = Convert.ToInt32(Console.ReadKey());
        while (!(statIndex2 > 0 && statIndex2 <= 5))
        {
            statIndex2 = Convert.ToInt16(Console.ReadKey());
            Console.WriteLine("Invalid Value,Please Try Again");
        }
    }

但是,当我尝试将readkey转换为int时,它会出现一个错误,说:

此行给出了错误:

char holder = Convert.ToChar(Console.ReadKey());

发生了"系统"类型的例外。 在mscorlib.dll

其他信息:无法施放类型的对象 'System.ConsoleKeyInfo'tote'System.Iconvertible'。

有人可以解释这意味着什么以及我如何解决它?

肯定该行Convert.ToInt16(Console.ReadKey())导致例外,由于失败转换,我建议您这样使用:

  int myNumber = (int)(Console.ReadKey().KeyChar);

由于Console.ReadKey()返回ConsoleKeyInfo,因此.KeyChar将为您提供相应的字符值,可以轻松地使用隐式转换将其转换为整数。但这也将给出字符的ASCII值。

您的另一个选项是TryParse,因此您也可以识别转换结果。那就是代码是这样的:

int myNumber;
if (!int.TryParse(Console.ReadKey().ToString(), out myNumber))
{
    Console.WriteLine("Conversion faild");
}
// myNumber holds the result

最新更新