我在 VB.net 中遇到了可空值的意外影响。有问题的对象定义了一个属性:
Public Property Value As Int32?
当我尝试使用
IIf
合并值时, 我得到一个空异常cmd.Parameters.AddWithValue("@HOValue", IIf(headOffice.Value.HasValue, headOffice.Value .Value, DBNull.Value))
在 C# 中,我知道可空对象没有隐式转换,因此您不能使用
??
,但为什么在 VB.NET 中评估 IIf 的第一部分?
最佳答案
这样做的原因是 Iif
是一个函数,所以true
值和 false
在条件之前评估值。
相反,使用 If
IE。:
cmd.Parameters.AddWithValue("@HOValue", If(headOffice.Value.HasValue, headOffice.Value.Value, DBNull.Value)) ' Assuming you've already checked that headOffice.Value IsNot Nothing
关于.net - VB.NET 可空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416777/