如何将 Console.Readkey 转换为 int c#
How do I convert a Console.Readkey to an int c#
我正在尝试将用户输入键转换为 int,用户将输入 1 到 6 之间的数字。
这是我目前在一个方法中所拥有的,它没有工作,但抛出格式异常未得到处理。
var UserInput = Console.ReadKey();
var Bowl = int.Parse(UserInput.ToString());
Console.WriteLine(Bowl);
if (Bowl == 5)
{
Console.WriteLine("OUT!!!!");
}
else
{
GenerateResult();
}
}
同样:
ConsoleKeyInfo info = Console.ReadKey();
int val;
if (int.TryParse(info.KeyChar.ToString(), out val))
{
Console.WriteLine("You pressed " + val.ToString());
}
只是说您正在尝试将 System.ConsoleKeyInfo
转换为 int
。
在您的代码中,当您调用 UserInput.ToString()
时,您得到的是代表当前对象 的字符串 ,而不是 value
或 Char
如你所料。
要获得控股权 Char
作为 String
,您可以使用 UserInput.KeyChar.ToString()
此外,在尝试使用 int.Parse
方法之前,您必须检查 ReadKey
是否有 digit
。因为 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();
}
这是一个扩展 class,它的可扩展性更强,而不仅仅是整数:
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}.");
}
}
}
有用于数值的控制台键。 ConsoleKey.D5 用于 5.
代码块可以re-written为-
var bowl = -1;
var userInput = Console.ReadKey();
if(userInput.Key == ConsoleKey.D5)
{
bowl = 5;
}
这是没有错误检查的简短答案。
int.Parse(Console.ReadKey().KeyChar.ToString());
我正在尝试将用户输入键转换为 int,用户将输入 1 到 6 之间的数字。
这是我目前在一个方法中所拥有的,它没有工作,但抛出格式异常未得到处理。
var UserInput = Console.ReadKey();
var Bowl = int.Parse(UserInput.ToString());
Console.WriteLine(Bowl);
if (Bowl == 5)
{
Console.WriteLine("OUT!!!!");
}
else
{
GenerateResult();
}
}
同样:
ConsoleKeyInfo info = Console.ReadKey();
int val;
if (int.TryParse(info.KeyChar.ToString(), out val))
{
Console.WriteLine("You pressed " + val.ToString());
}
只是说您正在尝试将 System.ConsoleKeyInfo
转换为 int
。
在您的代码中,当您调用 UserInput.ToString()
时,您得到的是代表当前对象 的字符串 ,而不是 value
或 Char
如你所料。
要获得控股权 Char
作为 String
,您可以使用 UserInput.KeyChar.ToString()
此外,在尝试使用 int.Parse
方法之前,您必须检查 ReadKey
是否有 digit
。因为 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();
}
这是一个扩展 class,它的可扩展性更强,而不仅仅是整数:
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}.");
}
}
}
有用于数值的控制台键。 ConsoleKey.D5 用于 5.
代码块可以re-written为-
var bowl = -1;
var userInput = Console.ReadKey();
if(userInput.Key == ConsoleKey.D5)
{
bowl = 5;
}
这是没有错误检查的简短答案。
int.Parse(Console.ReadKey().KeyChar.ToString());