【问题标题】:C# Conversion of ReadKey() to intC# 将 ReadKey() 转换为 int
【发布时间】:2017-05-05 05:31:31
【问题描述】:

我是 C# 新手,被告知要创建一个基于文本的 Pokemon 战斗模拟器,所以在下面的代码中,我有一个方法来获取用户输入并决定 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());

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

附加信息:无法转换类型的对象 'System.ConsoleKeyInfo' 输入 'System.IConvertible'。

谁能解释一下这是什么意思以及我该如何解决?

【问题讨论】:

  • 哪一行抛出异常?

标签: c# casting int type-conversion readkey


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-21
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2020-07-08
    • 2018-10-09
    • 2011-05-02
    相关资源
    最近更新 更多