2010-01-18 91 views

回答

13

编辑:这应该是在VB.NET 10根据this blog post可能。如果你使用它,那么你可以有:

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) 

对于超过10 VB.NET其它版本:

您的要求是不可能的。您应该使用可选参数或可以为空。此签名无效:

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

完美的答案..感谢了很多.. – 2010-01-19 04:09:51

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 
1

您也可以使用object:

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

End Sub

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 
相关问题