如何将Console.Readkey转换为int c#

问题描述 投票:2回答:4

我试图将用户输入密钥转换为int,用户将输入1到6之间的数字。

这是我到目前为止坐在一个方法中,它没有工作,但抛出格式异常是未处理的。

        var UserInput = Console.ReadKey();



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

        Console.WriteLine(Bowl);

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

    }

谢谢你的帮助!

c# int console.readkey
4个回答
12
投票

简单地说你试图将System.ConsoleKeyInfo转换为int

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

要获得持有Char作为String你可以使用UserInput.KeyChar.ToString()

此外,在尝试使用ReadKey方法之前,必须先检查digit是否有int.Parse。因为Parse方法在无法转换数字时抛出异常。

所以看起来像这样,

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();
}

0
投票

同理:

ConsoleKeyInfo info = Console.ReadKey();
int val;
if (int.TryParse(info.KeyChar.ToString(), out val))
{
    Console.WriteLine("You pressed " + val.ToString());
}

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}.");
        }
    }
}

〜干杯


0
投票

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

代码块可以重写为 -

var bowl = -1;
var userInput = Console.ReadKey();
if(userInput.Key == ConsoleKey.D5)
{
  bowl = 5; 
}
© www.soinside.com 2019 - 2024. All rights reserved.