static void Main(string[] args) { int num = 0; bool result = false; while (!result) { Console.WriteLine("input:"); string input = Console.ReadLine(); result = int.TryParse(input, out num); } Console.WriteLine("success"); Console.ReadKey(); }
Dim indata As String = "123456" Try If indata = CInt(indata).ToString Then '/// 是整型 Else '/// 不是整型 End If Catch ex As Exception '/// 连数都不是. End Try
用VB的函数 IsNumeric 也可以.比用 TRY 要好. Dim indata As String = "123456" If IsNumeric(indata) AndAlso indata = CInt(indata).ToString Then '/// 是整型 Me.Text = indata Else '/// 不是整数 End If
string m = "aa"; int b = 0; bool rlt = int.TryParse(m, out b);
//正则匹配
string str = Console.ReadLine();
string pattern = "^[0-9]*[1-9][0-9]*$";
Regex reg = new Regex(pattern);
while (!reg.IsMatch(str))
{
Console.WriteLine("非法输入,请重新输入");
str = Console.ReadLine();
}
{
int num = 0;
bool result = false;
while (!result)
{
Console.WriteLine("input:");
string input = Console.ReadLine();
result = int.TryParse(input, out num);
} Console.WriteLine("success"); Console.ReadKey();
}
try
{
string input = Console.ReadLine();
Convert.ToInt32(input);
Console.WriteLine(input);
}
catch
{
Console.WriteLine("请输入与整形");
}可以判断任何类型。
但我的变量是A与B啊
不需要转换,而是返回。C#的异常处理我还没学到
Try
If indata = CInt(indata).ToString Then
'/// 是整型
Else
'/// 不是整型
End If
Catch ex As Exception
'/// 连数都不是.
End Try
If IsNumeric(indata) AndAlso indata = CInt(indata).ToString Then
'/// 是整型
Me.Text = indata
Else
'/// 不是整数
End If
int b = 0;
bool rlt = int.TryParse(m, out b);
这也是一种转换方式。专用于字符串转换为值类型 。