Integer.TryParse - 更好的方法?

Rya*_*ith 33 vb.net tryparse

我发现自己经常需要使用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.

  • 恭喜,汤姆,你已经采取了一个非常好的简洁答案,并把它变成了一篇糊涂的500字的文章.:-) (5认同)
  • +1,C#注释与问题无关,因为它指定了vb.net. (4认同)
  • 在我的版本中添加了'Nothing'和+1 (2认同)

Ton*_*nyB 7

由于您使用的是VB.net,因此可以使用IsNumeric函数

If IsNumeric(myInt) Then
    'Do Suff here
End If
Run Code Online (Sandbox Code Playgroud)

  • IsNumeric仅在.NET中用于传统支持.TryParse是更好的选择. (11认同)
  • 你不需要VB,"VB运行时"是.NET框架的一部分,从C#开始工作得很好 (3认同)
  • 注意IsNumeric,即使对于某些非Integer值,它也会返回true.从MSDN页面"如果Expression的数据类型是Boolean,Byte,Decimal,Double,Integer,Long,SByte,Short,Single,UInteger,ULong或UShort,或者包含其中一种数字类型的Object,则IsNumeric返回True如果Expression是一个可以成功转换为数字的Char或String,它也会返回True." (2认同)

yfe*_*lum 5

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)