提问人:cingram93 提问时间:8/22/2023 最后编辑:Heretic Monkeycingram93 更新时间:8/23/2023 访问量:67
如何在 C# 中验证用户输入?[已结束]
How to validate user input in C#? [closed]
问:
我试图要求用户输入数字 1-10 并验证他们的响应。
我是 C# 的新手,我正在上课时学习它,并且没有任何编程背景。难以记住所有术语及其用法
Console.Writeline(“Enter a number between 1-10”)
String (num1)
{
case “one”:
case “two”:
case “three”:
Console.Writeline(“Picked number 1,2,3,4,5,6,7,8,9, or 10”);
break;
答:
2赞
JonasH
8/22/2023
#1
一种常见的方法是使用辅助方法,确切的设计可能会有所不同,但这将是一个相当简单的选项,允许用户重试输入数字:
public static int ReadInt(string question, int min = int.MinValue, int max = int.MaxValue)
{
Console.WriteLine(question);
while(true){
var input = Console.ReadLine();
if(!int.TryParse(input, out var number)){
Console.WriteLine("Not an integer, try again");
continue;
}
if(number < min){
Console.WriteLine($" {number} smaller than {min}, try again");
continue;
}
if(number > max){
Console.WriteLine($" {number} larger than {max}, try again");
continue;
}
return number ;
}
}
如果要接受“one”而不是“1”之类的输入,则可能还需要考虑创建自己的解析方法。但是,对于任何大数或负数,这很容易变得复杂。
0赞
Karen Payne
8/23/2023
#2
查看包含文档的 NuGet 包 Spectre.Console。
以下内容没有像@jonasH那样教授基础知识,因此如果是这种情况,您可能希望回复那里,否则请继续此处。
下面是该方法提供的示例GetInt
- 输入类型在此处查看更多信息
new TextPrompt<int>
- 提供用户说明的文本
ValidationErrorMessage
输入错误类型的消息,例如字符串而不是 int。Validate
用于在输入超出范围或指示输入在范围内时返回错误消息。ValidationResult.Success()
该方法负责将文本输出到返回的值Choices
GetInt
internal partial class Program
{
static void Main(string[] args)
{
var dictionary = Choices();
Console.WriteLine($"You selected {dictionary[GetInt()]}");
Console.ReadLine();
}
/// <summary>
/// Text for int selected in <see cref="GetInt"/>
/// </summary>
/// <returns>Text for int selected</returns>
private static Dictionary<int, string> Choices()
{
Dictionary<int, string> dictionary = new Dictionary<int, string>()
{
{ 1, "one" }, { 2, "two" }, { 3, "three" }, { 4, "four" }, { 5, "five" },
{ 6, "six" }, { 7, "seven" }, { 8, "eight" }, { 9, "nine" }, { 10, "ten" },
{ 11, "none" },
};
return dictionary;
}
/// <summary>
/// Provides a prompt for an int between two numbers with
/// - colorization of screen output
/// - Validation to ensure input is within set range
/// - Range is 1 to 10 with 11 as an exit for aborting
/// </summary>
/// <returns>User selection</returns>
private static int GetInt() =>
AnsiConsole.Prompt(new TextPrompt<int>(
"Picked a [cyan]number[/] between [b]1[/] and [b]10[/] or [b]11[/] to exit")
.PromptStyle("cyan")
.ValidationErrorMessage("[red]That's not a valid value[/]")
.Validate(validator: x => x switch
{
<= 0 => ValidationResult.Error("[red]1 is min value[/]"),
>= 12 => ValidationResult.Error("[red]11 is max value[/]"),
_ => ValidationResult.Success(),
}));
}
评论