BC33107:二元“If”表达式中的第一个操作数必须是可以为 null 的类型或引用类型

If 表达式可以采用两个或三个参数。 当你只发送两个参数时,第一个参数必须是引用类型或可为空的值类型。 如果第一个参数的计算结果不是 Nothing,则返回其值。 如果第一个参数计算结果为 Nothing,则计算并返回第二个参数。

例如,以下代码包含两个 If 表达式,一个具有三个参数,一个具有两个参数。 表达式计算并返回相同的值。

' firstChoice is a nullable value type.
Dim firstChoice? As Integer = Nothing
Dim secondChoice As Integer = 1128
' If expression with three arguments.
Console.WriteLine(If(firstChoice IsNot Nothing, firstChoice, secondChoice))
' If expression with two arguments.
Console.WriteLine(If(firstChoice, secondChoice))

以下表达式会导致此错误:

Dim choice1 = 4
Dim choice2 = 5
Dim booleanVar = True

' Not valid.
'Console.WriteLine(If(choice1 < choice2, 1))
' Not valid.
'Console.WriteLine(If(booleanVar, "Test returns True."))

错误 ID:BC33107

更正此错误

  • 如果你无法更改代码以使第一个参数为可空值类型或引用类型,请考虑转换为三参 If 数表达式,或转换为 If...Then...Else 语句。
Console.WriteLine(If(choice1 < choice2, 1, 2))
Console.WriteLine(If(booleanVar, "Test returns True.", "Test returns False."))

另请参阅