5

我正在尝试将用户输入键转换为 int,用户将输入 1 到 6 之间的数字。

到目前为止,这就是我坐在一个方法中的内容,它不起作用,但未处理引发格式异常。

        var UserInput = Console.ReadKey();



        var Bowl = int.Parse(UserInput.ToString());

        Console.WriteLine(Bowl);

       if (Bowl == 5)
        {
            Console.WriteLine("OUT!!!!");
        }
        else
        {
            GenerateResult();
        }

    }
4

5 回答 5

14

简单地说,您正在尝试转换System.ConsoleKeyInfoint.

在您的代码中,当您调用时UserInput.ToString(),您得到的是代表当前对象的字符串,而不是持有valueChar您期望的。

要获得控股权CharString您可以使用UserInput.KeyChar.ToString()

此外,您必须在尝试使用方法之前检查ReadKeya 。因为方法在转换数字失败时会抛出异常。digitint.ParseParse

所以它看起来像这样,

int Bowl; // Variable to hold number

ConsoleKeyInfo UserInput = Console.ReadKey(); // Get user input

// We check input for a Digit
if (char.IsDigit(UserInput.KeyChar))
{
     Bowl = int.Parse(UserInput.KeyChar.ToString()); // use Parse if it's a Digit
}
else
{
     Bowl = -1;  // Else we assign a default value
}

你的代码:

int Bowl; // Variable to hold number

var UserInput = Console.ReadKey(); // get user input

int Bowl; // Variable to hold number

// We should check char for a Digit, so that we will not get exceptions from Parse method
if (char.IsDigit(UserInput.KeyChar))
{
    Bowl = int.Parse(UserInput.KeyChar.ToString());
    Console.WriteLine("\nUser Inserted : {0}",Bowl); // Say what user inserted 
}
else
{
     Bowl = -1;  // Else we assign a default value
     Console.WriteLine("\nUser didn't insert a Number"); // Say it wasn't a number
}

if (Bowl == 5)
{
    Console.WriteLine("OUT!!!!");
}
else
{
    GenerateResult();
}
于 2015-03-10T02:29:01.547 回答
0

相似地:

ConsoleKeyInfo info = Console.ReadKey();
int val;
if (int.TryParse(info.KeyChar.ToString(), out val))
{
    Console.WriteLine("You pressed " + val.ToString());
}
于 2015-03-10T02:20:30.357 回答
0

这是一个扩展类,使其更具可扩展性,而不仅仅是整数:

using System;

/// <summary>
/// Extension methods for <see cref="ConsoleKeyInfo"/>
/// </summary>
public static class ConsoleKeyInfoExtensions
{
    /// <summary>
    /// Attempts to cast the <see cref="ConsoleKeyInfo.KeyChar"/> value from the <paramref name="instance"/> to <typeparamref name="T"/>.
    /// </summary>
    /// <typeparam name="T">The generic type to cast to.</typeparam>
    /// <param name="instance">The <see cref="ConsoleKeyInfo"/> to extract the value from</param>
    /// <returns>Returns the value in the <see cref="ConsoleKeyInfo.KeyChar"/> as <typeparamref name="T"/></returns>
    /// <exception cref="InvalidCastException">If there is an issue with the casting.  For example, boolean is not valid.</exception>
    /// <exception cref="ArgumentNullException">If the <paramref name="instance"/> is null.</exception>
    public static T GetValue<T>(this ConsoleKeyInfo instance)
    {
        if (instance == null)
            throw new ArgumentNullException(nameof(instance));

        var stringValue = instance.KeyChar.ToString();

        try
        {
            return (T)Convert.ChangeType(stringValue, typeof(T));
        }
        catch
        {
            throw new InvalidCastException($"Unable to cast a {nameof(ConsoleKeyInfo.KeyChar)} to a type of {typeof(T).FullName}.");
        }
    }
}
于 2017-10-16T13:43:54.337 回答
0

有数值的 ConsoleKeys。ConsoleKey.D5 用于 5。

代码块可以重写为 -

var bowl = -1;
var userInput = Console.ReadKey();
if(userInput.Key == ConsoleKey.D5)
{
  bowl = 5; 
}
于 2018-04-12T00:20:04.003 回答
0

这是没有错误检查的简短答案。

int.Parse(Console.ReadKey().KeyChar.ToString());
于 2019-11-17T20:38:13.983 回答