如何在VB.NET中创建可为空的数字可选参数?
问问题
13617 次
4 回答
16
编辑:根据这篇博文,这在 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
于 2010-01-18T13:44:02.527 回答
6
你不能,所以你将不得不使用重载来代替:
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
于 2010-01-18T13:47:50.623 回答
2
您还可以使用对象:
Public Sub DoSomething(Optional ByVal someInteger As Object = Nothing)
If someInteger IsNot Nothing Then
... Convert.ToInt32(someInteger)
End If
结束子
于 2011-10-07T15:26:40.100 回答
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
于 2014-11-29T12:54:53.103 回答