vb.net - 为什么不能用“?” 可空类型的运算符
问题描述
我有这行代码
Dim result = myStuff.FirstOrDefault(Function (t) t.PrimaryKey = mine.ID?.Value)
右侧ID
是 of Integer?
,左侧始终是integer
。
但这说不能解决。Value
解决方案
为了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
. 这里似乎不是你想要的。
推荐阅读
- java - 在 IE 中打开新窗口而不是 selenium web 驱动程序管理器中的新选项卡
- html - Bootstrap折叠元素行高问题
- google-cloud-platform - 如何在 GCP Cloud VPN 和我的 PC 之间建立 VPN 隧道?
- laravel - 我正在尝试更新数据,但使用 laravel 时出错
- oracle - Oracle Apex-如何在 LOV 内的选择列表中显示数字范围
- javascript - 如何在类模块外导出变量
- javascript - 在哪里添加用于切换按钮文本的代码?
- apache-flink - FlinkKafkaConsumer 从主题开始读取
- typescript - 重新导出命名的 typescript 接口会引发错误
- sql-server - 如果用户是用户分配托管标识,则确定 Azure SQL Server 中的用户名