Cod*_*ray 94

是的,只要您使用的是VB 9或更高版本(包含在Visual Studio 2008中).

您可以使用重载If运算符的版本来仅接受两个参数:

Dim myVar? As Integer = Nothing
Console.WriteLine(If(myVar, 7))
Run Code Online (Sandbox Code Playgroud)

更多信息可以发现这里在用VB.NET团队博客文章.

(是的,这是一个运算符,即使它看起来像一个函数.它将编译为与C#中"正确的"空合并运算符相同的IL.)

Dim b As Boolean?
Console.WriteLine("{0}.", If(b, "this is expected when b is nothing"))
'output: this is expected when b is nothing.

b = False
Console.WriteLine("{0}.", If(b, "this is unexpected when b is false"))
'output: False.

b = True
Console.WriteLine("{0}.", If(b, "this is unexpected when b is true"))
'output: True.
Run Code Online (Sandbox Code Playgroud)


See*_*arp 7

根据这个问题,似乎答案是If()

  • 如果您发现重复的问题,请将问题标记为重复,而不是发布链接到重复问题的答案.这有助于减少网站的混乱.如果您认为可以*为问题增加值*,则仅发布答案.谢谢! (4认同)

Meh*_*dad -3

编号 使用GetValueOrDefault; 这就是它存在的原因!

  • 即使不需要,“GetValueOrDefault(ByVal default As T)”也会强制评估默认参数,空合并运算符仅在“HasValue”为 false 时才会评估默认值。 (2认同)