Integer.TryParse-更好的方法? [英] Integer.TryParse - a better way?

查看:214
本文介绍了Integer.TryParse-更好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己经常需要使用Integer.TryParse来测试值是否为整数.但是,当您使用TryParse时,必须将引用变量传递给该函数,因此我发现自己总是需要创建一个空白整数来传递.通常看起来像这样:

I find myself often needing to use Integer.TryParse to test if a value is an integer. However, when you use TryParse, you have to pass a reference variable to the function, so I find myself always needing to create a blank integer to pass in. Usually it looks something like:

Dim tempInt as Integer
If Integer.TryParse(myInt, tempInt) Then

考虑到我想要的只是一个简单的True/False响应,我发现这很麻烦.有没有更好的方法来解决这个问题?为什么没有重载的函数可以传递要测试的值并获得true/false响应?

I find this to be quite cumbersome considering that all I want is a simple True / False response. Is there a better way to approach this? Why isn't there an overloaded function where I can just pass the value I want to test and get a true / false response?

推荐答案

无需声明整数.

If Integer.TryParse(intToCheck, 0) Then

If Integer.TryParse(intToCheck, Nothing) Then


如果您具有.Net 3.5的功能,则可以为字符串创建扩展方法.


If you have .Net 3.5 ability you can create an extension method for strings.

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

然后致电:

If value.IsInteger() Then


对不起,我不知所措,但是您也可以将其添加到.Net 3.5中的MyExtensions类中,除非您需要验证,不要担心.


Sorry, getting carried away I know, but also you can add this to the MyExtensions class above in .Net 3.5 and not worry unless you need validations.

<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

然后只需使用

value.ToInteger()

如果它不是有效的Integer,它将返回0.

This will return 0 if it isn't a valid Integer.

这篇关于Integer.TryParse-更好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆