如何在VB.NET中创建Nullable可选数字(整数/双精度)参数?

时间:2010-01-18 13:28:59

标签: vb.net nullable numeric optional-parameters

如何在VB.NET中创建可以为空的数字可选参数?

4 个答案:

答案 0 :(得分:15)

编辑:根据this blog post,这应该可以在VB.NET 10中实现。如果您正在使用它,那么您可以:

Public Sub DoSomething(Optional ByVal someInteger As Integer? = Nothing)
    Console.WriteLine("Result: {0} - {1}", someInteger.HasValue, someInteger)
End Sub

' use it
DoSomething(Nothing)
DoSomething(20)

对于VB.NET 10以外的版本:

您的请求无法执行。您应该使用可选参数,或者可以为空。此签名无效:

Public Sub DoSomething(Optional ByVal someInteger As Nullable(Of Integer) _
                        = Nothing)

您将收到此编译错误:“可选参数不能包含结构类型。”

如果你正在使用可空,那么如果你不想传递一个值,则将其设置为Nothing。选择以下选项:

Public Sub DoSomething(ByVal someInteger As Nullable(Of Integer))
    Console.WriteLine("Result: {0} - {1}", someInteger.HasValue, someInteger)
End Sub

Public Sub DoSomething(Optional ByVal someInteger As Integer = 42)
    Console.WriteLine("Result: {0}", someInteger)
End Sub

答案 1 :(得分:5)

你不能这样做,所以你不得不做过载:

Public Sub Method()
  Method(Nothing) ' or Method(45), depending on what you wanted default to be
End Sub

Public Sub Method(value as Nullable(Of Integer))
  ' Do stuff...
End Sub

答案 2 :(得分:2)

您还可以使用对象:

Public Sub DoSomething(Optional ByVal someInteger As Object = Nothing)
If someInteger IsNot Nothing Then
  ... Convert.ToInt32(someInteger)
End If

End Sub

答案 3 :(得分:0)

我在VS2012版本中想出来就像

Private _LodgingItemId As Integer?

Public Property LodgingItemId() As Integer?
        Get
            Return _LodgingItemId
        End Get
        Set(ByVal Value As Integer?)
            _LodgingItemId = Value
        End Set
    End Property

Public Sub New(ByVal lodgingItem As LodgingItem, user As String)
        Me._LodgingItem = lodgingItem
        If (lodgingItem.LodgingItemId.HasValue) Then
            LoadLodgingItemStatus(lodgingItem.LodgingItemId)
        Else
            LoadLodgingItemStatus()
        End If
        Me._UpdatedBy = user
    End Sub

Private Sub LoadLodgingItemStatus(Optional ByVal lodgingItemId As Integer? = Nothing)
    ''''statement 
End Sub