在 .Net 中使用新的空条件运算符 shorthand 功能时分配默认值?

Assign a default value when using the NEW Null-Conditional operator shorthand feature in .Net?

.Net 中新的 Null 条件运算符 shorthand 功能使我们能够编写如下简洁的代码:

Dim x = customer.Address?.Country

如果 customer.Address 为 null,新的语言功能是否提供提供默认值的方法?

目前我使用以下代码:

Dim x = If(customer.Address is nothing, "No Address", customer.Address?.Country)

您可以使用 Or 运算符。 此运算符确定变量是否有效,如果它 不是 ,则分配 or 的值。

对于你的情况,你可以使用:

Dim x = customer.Address.Country Or "No Address"

而不是

Dim x = If(customer.Address is nothing, "No Address", customer.Address?.Country)

当然,确实意味着这些变量可以有多种类型;您应该执行额外的检查以确保不同的对象类型不会破坏您的程序。

另一个例子(DomainId1):

Dim num = System.Threading.Thread.GetDomainID() Or 0
Console.WriteLine(CStr(num))
Console.Read()

控制台写出1,因为它是有效的

但是,如果我们将其切换为使用 0 Or System.Threading.Thread.GetDomainID(),我们仍然会得到 1,因为 0 不会被视为 'valid'。

如果两个值都有效,则使用最右边的变量。