首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IsNumeric在计算对象时引发FormatException

IsNumeric在计算对象时引发FormatException
EN

Stack Overflow用户
提问于 2012-04-05 23:35:56
回答 2查看 942关注 0票数 2

我正在使用visual studio 2008为windows CE 6.0开发软件,紧凑框架。

我有这种“奇怪的?”isNumeric方法有问题。有没有其他更好的方法来做这项工作?为什么让我成为一个例外?(两个在FormatException类型的facts...both中)

谢谢

代码语言:javascript
复制
dim tmpStr as object = "Hello"
if isNumeric(tmpStr) then    // EXCEPTIONs on this line
    // It's a number
else
    // it's a string
end if
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-05 23:43:46

尽管IsNumeric的文档中没有列出FormatException,但它确实是可以抛出的异常之一。抛出它的情况是

  • 传递了一个字符串值
  • 该字符串没有0x&H前缀

不过,我找不到任何理由来解释这种行为。我能够辨别它的唯一方法就是深入研究reflector中的实现。

解决这个问题的最好方法似乎是定义一个包装器方法

代码语言:javascript
复制
Module Utils
  Public Function IsNumericSafe(ByVal o As Object) As Boolean
    Try
      Return IsNumeric(o)
    Catch e As FormatException
      Return False
    End Try
  End Function
End Module
票数 5
EN

Stack Overflow用户

发布于 2012-04-05 23:43:10

出现这个错误的原因实际上是因为CF不包含TryParse方法。另一种解决方案是使用正则表达式:

代码语言:javascript
复制
Public Function CheckIsNumeric(ByVal inputString As String) As Boolean
    Return Regex.IsMatch(inputString, "^[0-9 ]+$")
End Function 

编辑

下面是一个更全面的正则表达式,它可以匹配任何类型的数字:

代码语言:javascript
复制
Public Function IsNumeric(value As String) As Object

    'bool variable to hold the return value
    Dim match As Boolean

    'regula expression to match numeric values
    Dim pattern As String = "(^[-+]?\d+(,?\d*)*\.?\d*([Ee][-+]\d*)?$)|(^[-+]?\d?(,?\d*)*\.\d+([Ee][-+]\d*)?$)"

    'generate new Regulsr Exoression eith the pattern and a couple RegExOptions
    Dim regEx As New Regex(pattern, RegexOptions.Compiled Or RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace)

    'tereny expresson to see if we have a match or not
    match = If(regEx.Match(value).Success, True, False)

    'return the match value (true or false)
    Return match

End Function

有关更多详细信息,请参阅本文:http://www.dreamincode.net/code/snippet2770.htm

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10031626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档