检查字符串变量是否具有整数值

Kai*_*rne 14 vb.net string parsing integer visual-studio-2010

我正在开展一个项目,允许孩子们向圣诞老人发送信息.不幸的是,如果他们在AGE字段中输入字符串而不是整数,程序崩溃并返回从字符串"[exampleString]"到"Double"类型的转换无效.有没有办法检查他们是否输入了整数?这是代码.

If childAge > 0 And childAge < 150 Then
    fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
    fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
Run Code Online (Sandbox Code Playgroud)

谢谢,凯:)

Sty*_*xxy 42

一个非常简单的技巧是尝试将字符串解析为Integer.如果成功,则为整数(惊喜).

Dim childAgeAsInt As Integer
If Integer.TryParse(childAge, childAgeAsInt) Then
    ' childAge successfully parsed as Integer
Else
    ' childAge is not an Integer
End If
Run Code Online (Sandbox Code Playgroud)


小智 6

补充 Styxxy 的响应,如果您不需要结果,只需将其替换为 vbNull:

If Integer.TryParse(childAge, vbNull) Then
Run Code Online (Sandbox Code Playgroud)