.net - CType 和类型转换异常

标签 .net vb.net winapp

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

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

最佳答案

使用Int32.TryParse :

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

这会处理“”以及用户可能输入的任何其他无效值(即非数字)的情况。

关于.net - CType 和类型转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5120445/

相关文章:

c# - .Net 对结构类型的泛型约束

c# - AutoMapper 2.1.265 中缺少成员

c# - 什么是NullReferenceException,我该如何解决?

c# - 我如何预先设置流?

asp.net - VB.NET创建两列CheckboxList

c# - Windows 应用拼写检查

c# - 当我将鼠标悬停在子控件上时会触发鼠标事件

.net - 如何使用计算器(桌面应用程序)附加我的 wpf 窗口?

.net - 在 .NET 中解析 TeamCity(Java?)生成的时间戳?

c# - 如何在 Windows Phone 7 上将 BitmapImage 调整为 50x50?