C#将ReadKey()转换为int

时间:2016-12-20 04:24:14

标签: c# casting int type-conversion readkey

我是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());
  

发生了类型为“System.InvalidCastException”的未处理异常   在mscorlib.dll中

     

附加信息:无法投射类型的对象   'System.ConsoleKeyInfo'键入'System.IConvertible'。

有人可以解释这是什么意思以及如何解决它?

1 个答案:

答案 0 :(得分:-1)

肯定这一行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