为什么不能使用“?”可为空类型的运算符

时间:2020-04-28 15:06:16

标签: vb.net

我有这行代码

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

ID的右侧是Integer?,左侧总是integer

但这表示无法解决。Value

1 个答案:

答案 0 :(得分:3)

要从Integer中提取Integer?,您必须提供一个后备值,该值将在Integer?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

但是,如果您唯一想做的是将IntegerInteger?进行比较,则无需提取任何内容。您可以直接比较它们。

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

如果safe navigation operator(您的代码段中使用的那个)的操作数也是Nothing,它将简单地解析为Nothing。似乎不是您想要的。

相关问题