如果不能一起工作,带有内联的可空类型? [英] Nullable type with inline if cannot work together?

查看:25
本文介绍了如果不能一起工作,带有内联的可空类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

Dim widthStr As String = Nothing

这有效 - width 被分配 Nothing:

This works - width is assigned Nothing:

Dim width As Nullable(Of Double)
If widthStr Is Nothing Then
  width = Nothing
Else
  width = CDbl(widthStr)
End If

但这并没有 - width 变成 0.0(虽然它似乎是逻辑上相同的代码):

But this does not - width becomes 0.0 (although it seems to be logically identical code):

Dim width As Nullable(Of Double) = If(widthStr Is Nothing, Nothing, CDbl(widthStr))

为什么?有什么我可以做的事情吗?

Why? Is there anything I can do to make it work?

推荐答案

这归结为表达式的类型分析.

This all comes down to type analysis of expressions.

Nothing 是 VB.Net 中的神奇动物.它与 C# 中的 default(T) 大致相同.

Nothing is a magical beast in VB.Net. It's approximately the same as default(T) in C#.

因此,在尝试确定以下内容的最佳类型时:

As such, when trying to determine the best type for the following:

If(widthStr Is Nothing, Nothing, CDbl(widthStr))

第三个参数是 Double 类型.第二个参数可以转换为Double(因为Nothing 可以返回值类型的默认值).因此,If 的返回值类型被确定为Double.

The third argument is of type Double. The second argument is convertible to Double (because Nothing can return the default value of value types). As such, the type of the return value of If is determined to be Double.

只有在该类型分析结束后,才会关注分配给该表达式的变量的类型.并且 Double 可以分配给 Double? 而没有任何警告.

Only after that piece of type analysis has concluded is any attention paid to the type of the variable to which this expression is being assigned. And Double is assignable to Double? without any warnings.

没有干净的方法可以让您的 If() 表达式按照您的预期工作.因为在 VB.Net 中没有与 null 等效的东西.您需要(至少)在 If 的潜在结果的一侧或另一侧插入 DirectCast(或等效的)以强制类型分析查看Double? 而不是 Double.

There's no clean way to make your If() expression work how you expected. Because there's no equivalent to null in VB.Net. You'd need (at the least) to insert a DirectCast (or equivalent) on one side or another of the potential results of the If to force the type analysis to see Double? rather than Double.

这篇关于如果不能一起工作,带有内联的可空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆