【问题标题】:IsNumeric throw FormatException while evaluating an objectIsNumeric 在评估对象时抛出 FormatException
【发布时间】:2012-04-05 15:35:56
【问题描述】:

我正在使用 Visual Studio 2008 开发适用于 Windows CE 6.0、紧凑框架的软件。

我有这个“奇怪?” isNumeric 方法有问题。还有其他更好的方法来完成这项工作吗?为什么让我例外? (事实上​​有两个...都是 FormatException 类型)

谢谢

dim tmpStr as object = "Hello"
if isNumeric(tmpStr) then    // EXCEPTIONs on this line
    // It's a number
else
    // it's a string
end if

【问题讨论】:

  • 异常消息和堆栈跟踪是什么?
  • 我无法使用您在 Win CE 6 模拟器上提供的代码重现此问题。它属于else 块。
  • 即使没有处理异常,它也不会卡住软件,而是写入以控制两个异常。如果程序没有停留在该点但继续执行,我如何查看堆栈跟踪?它也出现在我的 else 语句中......但有 2 个错误

标签: .net vb.net visual-studio compact-framework windows-ce


【解决方案1】:

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

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

不过,我找不到这种行为的任何理由。我什至能够辨别它的唯一方法是深入研究反射器中的实现。

解决它的最佳方法似乎是定义一个包装方法

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

【讨论】:

  • 感谢您的回答......完美的愚蠢就是为这种情况抛出异常......不是吗?
  • @RiccardoNeri IsNumeric 方法会在非数字输入上引发异常似乎真的很奇怪,但现在就是这样。
  • 它不起作用:o 它在 try...catch 内的“isNumeric”行上给我同样的错误。
  • @RiccardoNeri 你是在调试器下运行它吗?如果是这样,只需点击“继续”,您应该可以跳过它。
  • 是的,我可以在没有卡住软件的情况下继续使用...使用连接的调试器。我只是想知道是否有更好的方法来做到这一点。为什么这不是更好?返回 Regex.IsMatch(inputString, "^[0-9.]+$")
【解决方案2】:

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

Public Function CheckIsNumeric(ByVal inputString As String) As Boolean
    Return Regex.IsMatch(inputString, "^[0-9 ]+$")
End Function 

编辑

这是一个更全面的正则表达式,应该匹配任何类型的数字:

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

【讨论】:

  • 这不会完全有用户正在寻找的保真度。 IsNumeric 处理除整数之外的许多场景,例如浮点数
  • 抱歉 Jared,为什么这不起作用?它不匹配带小数点的数字,对吗?
  • @RiccardoNeri 问题在于IsNumeric 函数不仅仅匹配原始数字。它还将匹配布尔表达式、实现IConvertible 的对象、vb.net 特定的十六进制表示法等......正则表达式永远不会具有IsNumeric 函数所具有的完整保真度。
猜你喜欢
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2017-03-24
  • 1970-01-01
  • 2014-08-22
相关资源
最近更新 更多