在.Net中使用新的Null-Conditional算子速记功能时分配默认值?(Assign a default value when using the NEW Null-Conditional operator shorthand feature in .Net?)

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

Dim x = customer.Address?.Country

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

目前我使用以下代码:

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

The new Null-conditional operator shorthand feature in .Net enables us write neat code like this:

Dim x = customer.Address?.Country

If customer.Address is null, does the new Language feature offer a way to supply default values?

Presently i use the following code:

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

最满意答案

您可以使用Or运算符。 此运算符确定变量是否有效,如果不是 ,则赋值or 'ed值。

在您的情况下,您可以使用:

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

代替

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

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

另一个例子( DomainId是1 ):

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

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

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

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

You can use the Or operator. This operator determines whether the variable is valid, and if it's not, assign the or'ed value.

In your case, you could use:

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

Instead of

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

Of course, that does mean these variables can have multiple types; you should perform additional checks to ensure the different object types do not break your program.

Another example (DomainId is 1):

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

The console writes out 1, as it's valid

However if we switch it around so 0 Or System.Threading.Thread.GetDomainID() is used, we'll still get 1 as 0 isn't seen as 'valid'.

If both values are valid, then the rightmost variable is used.

更多推荐