【问题标题】:Make An Integer Null制作一个整数 Null
【发布时间】:2011-04-07 10:11:09
【问题描述】:

我有一个更新函数,它通过数据集更新 sql server db 表。表中的字段之一是整数并接受空值。因此,当我填充更新函数时,我需要一种在函数需要整数时输入 null 的方法。

我试图这样做,但_intDLocation = "" 抛出异常

Dim _dLocation As String = udDefaultLocationTextEdit.Text
    Dim _intDLocation As Integer
    If _dLocation <> "" Then
        _intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
    Else
        'NEED HELP HERE
        _intDLocation = ""
    End If

【问题讨论】:

    标签: vb.net nullable


    【解决方案1】:

    整数不能设置为 Null。您必须通过在单词 Integer 后添加问号来使整数“可为空”。现在 _intDLocation 不再是一个普通的整数。它是Nullable(Of Integer) 的一个实例。

    Dim _dLocation As String = udDefaultLocationTextEdit.Text
    Dim _intDLocation As Integer?
    If _dLocation <> "" Then
        _intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
    Else
        _intDLocation = Nothing
    End If
    

    稍后,如果您想检查 null,您可以使用这种方便、易读的语法:

    If _intDLocation.HasValue Then
       DoSomething()
    End If
    

    在某些情况下,您需要将值作为实际整数访问,而不是可以为空的整数。对于这些情况,您只需访问

    _intDLocation.Value
    

    阅读有关 Nullable here 的所有信息。

    【讨论】:

      【解决方案2】:

      试试这个:

      Dim _dLocation As String = udDefaultLocationTextEdit.Text
      
      Dim _intDLocation As Nullable(Of  Integer)
      
      If Not String.IsNullOrEmpty(_dLocation) Then
           _intDLocation = Integer.Parse(_dLocation)
      End If
      

      【讨论】:

        【解决方案3】:

        我的应用程序使用了很多以空白开头的标签(Text 属性),但需要作为整数递增,所以我做了这个方便的函数:

            Public Shared Function Nullinator(ByVal CheckVal As String) As Integer
            ' Receives a string and returns an integer (zero if Null or Empty or original value)
            If String.IsNullOrEmpty(CheckVal) Then
                Return 0
            Else
                Return CheckVal
            End If
        End Function
        

        这是如何使用它的典型示例:

        Dim Match_Innings As Integer = Nullinator(Me.TotalInnings.Text)
        

        享受吧!

        【讨论】:

          【解决方案4】:
          _intDLocation = Nothing
          

          【讨论】:

          • 这和 _intDLocation = 0 一样
          猜你喜欢
          • 2021-12-25
          • 2012-02-10
          • 2017-01-01
          • 2015-04-22
          • 2015-12-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多