我发现自己经常需要使用Integer.TryParse来测试值是否为整数.但是,当你使用TryParse时,你必须将一个引用变量传递给函数,所以我发现自己总是需要创建一个空白整数来传入.通常它看起来像:
Dim tempInt as Integer
If Integer.TryParse(myInt, tempInt) Then
Run Code Online (Sandbox Code Playgroud)
考虑到我想要的只是一个简单的真/假响应,我觉得这很麻烦.有没有更好的方法来解决这个问题?为什么没有一个重载函数,我可以传递我想要测试的值并获得真/假响应?
Tom*_*son 83
无需声明整数.
If Integer.TryParse(intToCheck, 0) Then
Run Code Online (Sandbox Code Playgroud)
要么
If Integer.TryParse(intToCheck, Nothing) Then
Run Code Online (Sandbox Code Playgroud)
如果您具有.Net 3.5功能,则可以为字符串创建扩展方法.
Public Module MyExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Function IsInteger(ByVal value As String) As Boolean
If String.IsNullOrEmpty(value) Then
Return False
Else
Return Integer.TryParse(value, Nothing)
End If
End Function
End Module
Run Code Online (Sandbox Code Playgroud)
然后打电话给:
If value.IsInteger() Then
Run Code Online (Sandbox Code Playgroud)
对不起,我知道了,但你也可以将它添加到.Net 3.5上面的MyExtensions类中,除非你需要验证,否则不用担心.
<System.Runtime.CompilerServices.Extension()> _
Public Function ToInteger(ByVal value As String) As Integer
If value.IsInteger() Then
Return Integer.Parse(value)
Else
Return 0
End If
End Function
Run Code Online (Sandbox Code Playgroud)
然后简单地使用
value.ToInteger()
Run Code Online (Sandbox Code Playgroud)
如果它不是有效的Integer,则返回0.
由于您使用的是VB.net,因此可以使用IsNumeric函数
If IsNumeric(myInt) Then
'Do Suff here
End If
Run Code Online (Sandbox Code Playgroud)
public static class Util {
public static Int32? ParseInt32(this string text) {
Int32 result;
if(!Int32.TryParse(text, out result))
return null;
return result;
}
public static bool IsParseInt32(this string text) {
return text.ParseInt32() != null;
}
}
Run Code Online (Sandbox Code Playgroud)