3
Public Property Duration() As Integer
Get
  Try
    Return CType(Item(DurationColumn), Integer)
  Catch e As Global.System.InvalidCastException
    Throw New Global.System.Data.StrongTypingException("The value for column 'Duration' in table 'T_MembershipSale' is DBNull.", e)
  End Try
End Get
Set(ByVal value As Integer)
  Item(DurationColumn) = value
End Set
End Property

当用户想要分配整数""时会发生什么?Item(DurationColumn)我得到一个例外。有什么干净的解决方案可以避免这种情况并设置0""

4

4 回答 4

3

Use Int32.TryParse:

Dim number as Integer
If Not Int32.TryParse(DurationColumn, number) Then number = 0
return number

This handles the case of "", as well as any other invalid value (i.e. non-number) the user might enter.

于 2011-02-25T17:30:00.050 回答
0

TryCastInt32.TryParse

于 2011-02-25T17:33:27.863 回答
0

您可以使用IsNumeric

    number = If(IsNumeric(DurationColumn), CType(DurationColumn, Integer), 0)
于 2011-02-25T17:39:02.907 回答
0

您可以先将函数返回分配给变量,然后在转换前检查变量。

    Dim sRet As String = Item(DurationColumn)
    If Not String.IsNullOrEmpty(sRet) Then Convert.ToInt32(sRet)
于 2011-02-26T05:04:24.630 回答