C# 使用整数和int.tryparse进行输入验证
所以我几乎有2k行代码,我忘记了/我不知道如何在用户输入上设置输入值,例如C# 使用整数和int.tryparse进行输入验证,c#,C#,所以我几乎有2k行代码,我忘记了/我不知道如何在用户输入上设置输入值,例如 cw("Hello Please Enter your age"); cw("If you are in a Group Input the Age of the Youngest Member of the Group."); Age = Convert.ToInt32(Console.ReadLine()); 我想这样做,用户只能输入数字,我的程序在他
cw("Hello Please Enter your age");
cw("If you are in a Group Input the Age of the Youngest Member of the Group.");
Age = Convert.ToInt32(Console.ReadLine());
我想这样做,用户只能输入数字,我的程序在他们输入somels时不会崩溃
这是整个console.readlines程序中的一个常见问题
是否有一种方法可以让我在批准时只为数字和字母引入输入值
先谢谢你 这是我在稍加润色后要做的:
public static bool PromptForInt(string promptString, out int result, string helpString = null)
{
while (true)
{
Console.WriteLine(promptString);
var response = Console.ReadLine();
if (string.Equals(response, "Q", StringComparison.OrdinalIgnoreCase))
{
result = 0;
return false;
}
if (helpString != null && string.Equals(response, "H", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine(helpString);
continue; //skip back to the top of the loop
}
if (int.TryParse(response, out result))
{
return true;
}
}
}
您可以为其他类型(例如double或DateTime)修改类似的函数,始终使用typeName.TryParse。
在润色方面,如果用户没有输入Q、H或有效的int,您可能希望得到一条有用的错误消息。否则…您可以使用int.TryParse来解决您的问题。是的,尽管我写了一个直接控制台程序已经好几年/几十年了。编写一个简单的小函数,它接受提示和帮助字符串,并返回bool true=success,false=user determing to quit。在该例程中,输出提示字符串并读取用户的响应。他可以退出,请求帮助,或者在本例中输入一个适当的值,一个int。然后检查Q或H。如果两者都不存在,则使用int.TryParse并在失败时返回。哦,拜托,我确定这是一个dup,但你指的是一个没有接受答案的问题。我看到的第一个是用正则表达式测试一个数字。如果你向下滚动大约6个答案,你会发现一个有5票的答案使用了TryParse。我看到的最后一个有12票的答案也引用了TryParse。一定有更好的方法来指出这一点!!!