Comment créer un paramètre optionnel numérique nul dans VB.NET?Comment créer un paramètre Nullable Optional Numeric (entier/double) dans VB.NET?
4
A
Répondre
13
EDIT: cela devrait être possible dans VB.NET 10 selon this blog post. Si vous l'utilisez, vous pourriez avoir:
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)
Pour les versions autres que VB.NET 10:
Votre demande n'est pas possible. Vous devez utiliser un paramètre facultatif ou nullable. Cette signature est invalide:
Public Sub DoSomething(Optional ByVal someInteger As Nullable(Of Integer) _
= Nothing)
Vous obtiendrez cette erreur de compilation: "Les paramètres facultatifs ne peuvent pas avoir de types de structure."
Si vous utilisez une valeur Null, définissez-la sur Nothing si vous ne souhaitez pas lui transmettre de valeur. Choisissez entre ces options:
Public Sub DoSomething(ByVal someInteger As Nullable(Of Integer))
Console.WriteLine("Result: {0} - {1}", someInteger.HasValue, someInteger)
End Sub
ou
Public Sub DoSomething(Optional ByVal someInteger As Integer = 42)
Console.WriteLine("Result: {0}", someInteger)
End Sub
5
Vous ne pouvez pas, vous devrez faire avec une surcharge à la place:
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
Vous pouvez également utiliser un objet:
Public Sub DoSomething(Optional ByVal someInteger As Object = Nothing)
If someInteger IsNot Nothing Then
... Convert.ToInt32(someInteger)
End If
End Sub
0
je figure dehors en version VS2012 comme
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
réponse parfaite .. merci beaucoup .. –