简体   繁体   English

验证用户输入C#(控制台)

[英]Validate user input C# (console)

I have the following code: 我有以下代码:

aVariable =  int.Parse(Console.ReadLine());

One problem I have is I cannot find any support material to help validate the user input, for instance if the user pressed the letter a, this would simply kill the program. 我遇到的一个问题是我找不到任何支持材料来帮助验证用户输入,例如,如果用户按下了字母a,这只会杀死程序。

What can I do? 我能做什么? Where can I find a decent tutorial? 我在哪里可以找到一个体面的教程?

Rather than using the Parse method use TryParse instead. 而不是使用Parse方法而是使用TryParse

int age;

bool isValidInt = int.TryParse(Console.ReadLine(), out age);

You can use TryParse for this.. just google for this method. 你可以使用TryParse ..只需谷歌这个方法。 Or you can catch for exceptions to prevent your program to crash 或者您可以捕获异常以防止程序崩溃

int.Parse throws a FormatException, when the string cannot be parsed. 当无法解析字符串时,int.Parse抛出FormatException。 You can catch this exception and handle it, eg show an error message. 您可以捕获此异常并处理它,例如显示错误消息。

Another way is to use TryParse: 另一种方法是使用TryParse:

int number = 0;
bool result = Int32.TryParse(value, out number);
if (result)
{
   Console.WriteLine("Converted '{0}' to {1}.", value, number);         
}

Validating user input is no different in a console app than it is in a Winforms app. 验证用户输入在控制台应用程序中与在Winforms应用程序中的用户输入没有区别。 It's also very similar to validating user input in an ASP.NET app, except that you don't have the nice Validation controls. 它与在ASP.NET应用程序中验证用户输入非常相似,只是您没有很好的验证控件。

If you're coming from an ASP.NET background look at how people use CustomValidators - pay attention to the code-behind and ignore the client-side validation. 如果您来自ASP.NET背景,请查看人们如何使用CustomValidators - 注意代码隐藏并忽略客户端验证。

Also, you can use RegularExpressions in a Console app just as easily as you can in an ASP.NET app. 此外,您可以像在ASP.NET应用程序中一样轻松地在Console应用程序中使用RegularExpressions。

Probably the reason validation isn't mentioned specifically to Console apps is that validation of input is validation of input. 可能没有专门针对控制台应用程序提及验证的原因是输入验证是对输入的验证。 The methods are the same almost everywhere. 这些方法几乎无处不在。 The only difference with ASP.NET comparatively is the existence of custom controls that help do it for you. 与ASP.NET相比,唯一的区别是存在自定义控件,可以帮助您完成。

Use Int32.TryParse instead and test for a successful cast. 请改用Int32.TryParse并测试成功的Int32.TryParse

Int32 val;
if (Int32.TryParse(userInput, out val))
{
  // val is now the user input as an integer
}
else
{
  // bad user input
}

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

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