如何在 C# 中验证用户输入?[已结束]

How to validate user input in C#? [closed]

提问人:cingram93 提问时间:8/22/2023 最后编辑:Heretic Monkeycingram93 更新时间:8/23/2023 访问量:67

问:


想改进这个问题吗?通过编辑这篇文章添加详细信息并澄清问题。

3个月前关闭。

我试图要求用户输入数字 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; 
C# 验证 输入

评论

2赞 gunr2171 8/22/2023
你说的是switch语句吗?
1赞 gunr2171 8/22/2023
您能更清楚地了解您正在执行的验证类型吗?用英语而不是代码来解释它,并给出示例输入和输出。然后将您的代码尝试(请用代码块格式化)与您的要求相关联。
1赞 Luuk 8/22/2023
@kuga:请不要认为这是一个简单的问题。对你来说可能是,对其他人来说可能不是。也不建议参考聊天机器人,因为在那里正确提出问题决定了答案的正确性,但当你以错误的方式提出问题时,要准备好得到一个没有意义的答案。所以,一个更好的建议是上这门课(所有的人),然后开始在这里问 stackoverflow.com。

答:

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

该方法负责将文本输出到返回的值ChoicesGetInt

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

enter image description here