繁体   English   中英

C#将ReadKey()转换为int

[英]C# Conversion of ReadKey() to int

我是C#的新手,被告知要创建一个基于文本的Pokemon Battle Simulator,因此在下面的代码中,我有一种方法来获取用户输入并确定Pokemon获得哪种性质:

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.InvalidCastException'类型的未处理异常

附加信息:无法将类型为“ System.ConsoleKeyInfo”的对象转换为类型为“ 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM