' Variable first is a nullable type.
Dim first? As Integer = 3
Dim second As Integer = 6
' Variable first <> Nothing, so its value, 3, is returned.
Console.WriteLine(If(first, second))
second = Nothing
' Variable first <> Nothing, so the value of first is returned again.
Console.WriteLine(If(first, second))
first = Nothing second = 6
' Variable first = Nothing, so 6 is returned.
Console.WriteLine(If(first, second))
''' <summary>
''' Returns the first non-null T based on a collection of the root object and the args.
''' </summary>
''' <param name="obj"></param>
''' <param name="args"></param>
''' <returns></returns>
''' <remarks>Usage
''' Dim val as String = "MyVal"
''' Dim result as String = val.Coalesce(String.Empty)
''' *** returns "MyVal"
'''
''' val = Nothing
''' result = val.Coalesce(String.Empty, "MyVal", "YourVal")
''' *** returns String.Empty
'''
''' </remarks>
<System.Runtime.CompilerServices.Extension()> _
Public Function Coalesce(Of T)(ByVal obj As T, ByVal ParamArray args() As T) As T
If obj IsNot Nothing Then
Return obj
End If
Dim arg As T
For Each arg In args
If arg IsNot Nothing Then
Return arg
End If
Next
Return Nothing
End Function
Term Definition
---- ----------
argument2 Required. Object. Must be a reference or nullable type.
Evaluated and returned when it evaluates to anything
other than Nothing.
argument3 Required. Object.
Evaluated and returned if argument2 evaluates to Nothing.
' Variable first is a nullable type.
Dim first? As Integer = 3
Dim second As Integer = 6
' Variable first <> Nothing, so its value, 3, is returned.
Console.WriteLine(If(first, second))
second = Nothing
' Variable first <> Nothing, so the value of first is returned again.
Console.WriteLine(If(first, second))
first = Nothing
second = 6
' Variable first = Nothing, so 6 is returned.
Console.WriteLine(If(first, second))
如何处理两个以上的值(嵌套ifS)的示例:
Dim first? As Integer = Nothing
Dim second? As Integer = Nothing
Dim third? As Integer = 6
' The LAST parameter doesn't have to be nullable.
'Alternative: Dim third As Integer = 6
' Writes "6", because the first two values are "Nothing".
Console.WriteLine(If(first, If(second, third)))
' This statement prints TruePart, because the first argument is true.
Console.WriteLine(If(True, "TruePart", "FalsePart"))
' This statement prints FalsePart, because the first argument is false.
Console.WriteLine(If(False, "TruePart", "FalsePart"))
Dim number = 3
' With number set to 3, this statement prints Positive.
Console.WriteLine(If(number >= 0, "Positive", "Negative"))
number = -1
' With number set to -1, this statement prints Negative.
Console.WriteLine(If(number >= 0, "Positive", "Negative"))