是否有VB.NET内置的类似于C#空合并运算符的操作符?
可能重复问题:
在VB.NET中使用Coalesce运算符和条件运算符
是否有一个VB.NET等同于C#的??运算符的操作符?
是否有VB.NET内置的类似于C#空合并运算符的操作符?
可能重复问题:
在VB.NET中使用Coalesce运算符和条件运算符
是否有一个VB.NET等同于C#的??运算符的操作符?
是的,只要你使用VB 9或更高版本(包含在Visual Studio 2008中),就可以实现。
你可以使用重载了接受两个参数的If
运算符的版本。
Dim myVar? As Integer = Nothing
Console.WriteLine(If(myVar, 7))
更多信息可以在VB.NET团队的一篇博客文章这里找到。
(是的,这是一个操作符,即使它看起来像一个函数。它将编译成与C#中“正确”的null-coalescing操作符相同的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.
GetValueOrDefault
;那就是它存在的原因!GetValueOrDefault(ByVal default As T)
强制求值默认参数,即使其不是必需的,而 null 合并运算符只有在 HasValue
为 false 时才会求值默认参数。 - Lukazoid我不相信VB.Net内置了等效的运算符,但是这里有一个答案:null coalesce operator in VB.Net(8)。
Dim x = Obj?.Child?.AnotherChild?.Something?.AString
如果任何对象为null,则x是一个空字符串,否则如果所有对象都不为null,则设置x的值。 - Edamreed?.
是空值条件运算符(也称为安全导航运算符),而不是问题所询问的??
空值合并运算符。 - rob3c