简体   繁体   English

验证C#中的readline输入的最佳方法?

[英]Best way to verify readline input in C#?

Oh, 2 things: 1) It is a console application. 哦,有两件事:1)它是一个控制台应用程序。 2 ) I know it is in danish, but it doesn't really matter, its just an example of asking for some input. 2)我知道这是丹麦语,但这并不重要,它只是要求输入一些内容的示例。 The text and variables does not matter. 文本和变量无关紧要。

Alright, consider this simple input: It could be any sort of input question really. 好吧,考虑一下这个简单的输入:真的可能是任何形式的输入问题。

Console.WriteLine("Hvad er dit kundenummer: (Kun hele tal tilladt)");
string inputKnr = Console.ReadLine();
kundenummer = Convert.ToInt16(inputKnr);

Now, what if the customer types something wrong? 现在,如果客户输入了错误的内容怎么办? Such as a letter. 如信。 A try & catch would make sure the application does not break, but that is not the solution I want. 尝试并捕获将确保应用程序不会中断,但这不是我想要的解决方案。 I want it to say that you did it wrong, try again. 我想说您做错了,请再试一次。 Pretty classic right? 很经典吧?

But what is the best way to solve this solution? 但是解决该解决方案的最佳方法是什么? I have thought of this: 我想到了这一点:

bool fangetKundenummer = true;
while (fangetKundenummer)
{
Console.WriteLine("Hvad er dit kundenummer: (Kun hele tal tilladt)");
string inputKnr = Console.ReadLine();
try
{
    kundenummer = Convert.ToInt16(inputKnr);
    fangetKundenummer = false;
}
catch
{
    Console.WriteLine("Fejl. Prøv igen");
}
}

But it just doesn't seem like the right way to do it. 但这似乎不是正确的方法。

Also, just to mention it, this little application I am playing with has 4 input questions in a row . 另外,仅需提及,我正在玩的这个小应用程序连续4个输入问题 This would mean 4 times this nasty while() loop. 这意味着这个讨厌的while()循环的4倍。

You could also write a function. 您也可以编写一个函数。 Something like this (no reason to do it the right way, its just to illustrate a concept): 这样的事情(没有理由以正确的方式做,只是为了说明一个概念):

static void verifyInput()
{
    try
    {
        Console.WriteLine("question");
        input = Console.ReadLine();
        kundenummer = Convert.ToInt16(input)
    }
    catch
    {
        Console.WriteLine("Wrong. Do it over");
        verifyInput(); //start the function all over
    }
}

But you'd have to write a function for each and every input question, even though they might ask exactly for the same! 但是,您必须为每个输入问题编写一个函数,即使它们可能要求完全相同! (meaning perhaps all asking for an integer; but with a different question and variable). (意味着可能所有人都要求一个整数;但问题和变量不同)。

This doesn't seem much better than the while() solution. 这似乎没有while()解决方案更好。

Does anyone have a clever idea? 有人有聪明的主意吗?

Use Int16.TryParse and the equivalents for other numeric types. 使用Int16.TryParse和其他数字类型的等效项。 All of these return a Boolean result to indicate success or failure for parsing, and take an out parameter which is set to the result of the parsing (or 0 in case of failure). 所有这些都返回一个布尔结果,以指示解析成功或失败,并采用out参数设置为解析结果(如果失败,则为0)。 In your case you may want to wrap the call in a method to keep prompting: 在您的情况下,您可能希望将调用包装在一种方法中以保持提示:

static Int16 PromptForInt16(string prompt)
{
    while (true)
    {
        Console.Write(prompt);
        Int16 result;
        if (Int16.TryParse(Console.ReadLine(), out result))
        {
            return result;
        }
        Console.WriteLine("Sorry, invalid number entered. Try again.");
    }
}

You can use the TryParse pattern: 您可以使用TryParse模式:

string s; // for "is not valid" message
short val; // final value
while(!short.TryParse(s=Console.ReadLine(), out val)) {
    Console.WriteLine(s + " is not valid...");
}

Just for some variety, how about testing the string itself, instead of TryParse, which would require extra storage, and potentially an unneeded cast? 只是出于某种变化,如何测试字符串本身而不是TryParse,这将需要额外的存储空间,并且可能不需要进行转换?

static void Main(string[] args)
{
    var isFalse = "t".IsInt();
    var isTrue = "123".IsInt();
    var isAlsoFalse = "123.1".IsInt();

}

static bool IsInt(this IEnumerable<char> s)
{
    return s.All(x => char.IsNumber(x));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM