Как преобразовать консоль.Readkey к 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();
}
}
Спасибо за помощь!
4 ответов:
Просто сказал, что вы пытаетесь преобразовать
System.ConsoleKeyInfoвint.В коде, когда вы вызываете
UserInput.ToString(), Вы получаете строку , которая представляет текущий объект, а не удержаниеvalueилиChar, Как вы ожидаете.Чтобы получить холдинг
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(); }
Существуют Консолеки для числовых значений. ConsoleKey.D5-это для 5.
Блок кода может быть переписан как -
var bowl = -1; var userInput = Console.ReadKey(); if(userInput.Key == ConsoleKey.D5) { bowl = 5; }
Аналогично:
ConsoleKeyInfo info = Console.ReadKey(); int val; if (int.TryParse(info.KeyChar.ToString(), out val)) { Console.WriteLine("You pressed " + val.ToString()); }
Вот класс расширения, который делает его немного более расширяемым и не только для целых чисел:
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}."); } } }~ Ура
Comments