C# 限制if语句

C# 限制if语句,c#,if-statement,console-application,C#,If Statement,Console Application,这是一个非常基本的问题,但如何在if语句中只允许数字值? 例如,如果用户输入字符串作为id,它应该给出一个错误,表示只允许数值 Console.Write("Please enter your ID: "); int id = Int32.Parse(Console.ReadLine()); if () // what should I write here? { Console.WriteLine("Only Numeric value are allowed."); }else{ C

这是一个非常基本的问题,但如何在if语句中只允许数字值? 例如,如果用户输入字符串作为id,它应该给出一个错误,表示只允许数值

Console.Write("Please enter your ID: ");
int id = Int32.Parse(Console.ReadLine());
if () // what should I write here?
{
    Console.WriteLine("Only Numeric value are allowed.");
}else{
Console.WriteLine("My ID is {0}", id);}
使用


TryParse
如果解析失败,则一组方法不会引发异常,而是返回一个指示成功或失败的
bool

可以使用正则表达式,例如:

if(Regex.IsMatch("[0-9]") == false)

您应该使用以下方法在
if
中进行分析:


您可以使用
char.IsDigit
功能吗。。?仔细阅读并尝试一下。@BlueTrin是的,我想说的是,你根本不可能有if这个句子。如果字符串不是有效数字,则解析将引发异常。。所以
try{int id=Int32.Parse(Console.ReadLine());Console.WriteLine(“我的id是{0}”,id);}}}catch{Console.WriteLine(“只允许数值”);}
是一个选项。不是首选方法,因为需要对它进行两次解析
int.TryParse
为您完成所有操作。它给出了一个错误,提示“最佳重载方法有一些无效参数”。:/@samjohal,我的错,它应该是
Console.ReadLine
,而不是
Console.Read
。请阅读
,谢谢您的回复。它正在工作。
if(Regex.IsMatch("[0-9]") == false)
int id;

if (Int32.TryParse(Console.ReadLine(), out id))
{
    // it's an integer!
}
else
{
}