首页 > 解决方案 > 为什么不能用“?” 可空类型的运算符

问题描述

我有这行代码

Dim result = myStuff.FirstOrDefault(Function (t) t.PrimaryKey = mine.ID?.Value)

右侧ID是 of Integer?,左侧始终是integer

但这说不能解决。Value

标签: vb.net

解决方案


为了Integer从 an中提取 an,Integer?您必须提供一个备用值,以防您的Integer?is使用Nothing。该方法GetValueOrDefault正是这样做的。

请参见以下示例:

Dim x As Integer? = 7
Dim y As Integer? = Nothing
Dim z As Integer = 7

Console.WriteLine(If(z = x.GetValueOrDefault(-1), "yes", "no")) ' Prints yes
Console.WriteLine(If(z = y.GetValueOrDefault(-1), "yes", "no")) ' Prints no

但是,如果您只想将 anInteger与 an进行比较Integer?,则无需提取任何内容。您可以直接比较它们。

Dim x As Integer? = 7
Dim y As Integer? = Nothing
Dim z As Integer = 7

Console.WriteLine(If(z = x, "yes", "no")) ' Prints yes
Console.WriteLine(If(z = y, "yes", "no")) ' Prints no

安全导航运算符(在您的代码片段中使用的那个)将简单地解析为它Nothing的操作数是否也是Nothing. 这里似乎不是你想要的。


推荐阅读