避免 NullReferenceException
Version >= 7
要不然
Sub Main()
Dim elements As List(Of Integer) = Nothing
Dim average As Double = AverageElementsOrElse(elements)
Console.WriteLine(average) ' Writes 0 to Console
Try
'Throws ArgumentNullException
average = AverageElementsOr(elements)
Catch ex As ArgumentNullException
Console.WriteLine(ex.Message)
End Try
End Sub
Public Function AverageElementsOrElse(ByVal elements As IEnumerable(Of Integer)) As Double
' elements.Count is not called if elements is Nothing so it cannot crash
If (elements Is Nothing OrElse elements.Count = 0) Then
Return 0
Else
Return elements.Average()
End If
End Function
Public Function AverageElementsOr(ByVal elements As IEnumerable(Of Integer)) As Double
' elements.Count is always called so it can crash if elements is Nothing
If (elements Is Nothing Or elements.Count = 0) Then
Return 0
Else
Return elements.Average()
End If
End Function
Version >= 7
并且
Sub Main()
Dim elements As List(Of Integer) = Nothing
Dim average As Double = AverageElementsAndAlso(elements)
Console.WriteLine(average) ' Writes 0 to Console
Try
'Throws ArgumentNullException
average = AverageElementsAnd(elements)
Catch ex As ArgumentNullException
Console.WriteLine(ex.Message)
End Try
End Sub
Public Function AverageElementsAndAlso(ByVal elements As IEnumerable(Of Integer)) As Double
' elements.Count is not called if elements is Nothing so it cannot crash
If (Not elements Is Nothing AndAlso elements.Count > 0) Then
Return elements.Average()
Else
Return 0
End If
End Function
Public Function AverageElementsAnd(ByVal elements As IEnumerable(Of Integer)) As Double
' elements.Count is always called so it can crash if elements is Nothing
If (Not elements Is Nothing And elements.Count > 0) Then
Return elements.Average()
Else
Return 0
End If
End Function
Version >= 14.0
Visual Basic 14.0 引入了空条件运算符 ,允许以更清晰的方式重写函数,模仿示例的 AndAlso
版本的行为。