VB.NET 没有日期时间?数据读取器
VB.NET Nothing Datetime? dataReader
一个带有 if 内联的简单问题: 将 mydate 调暗为日期时间?
'版本 1(有效!)
If dtReader.IsDBNull(dtReader.GetOrdinal("mydate")) Then
mydate = Nothing
Else
mydate = dtReader.GetDateTime(dtReader.GetOrdinal("mydate"))
End If
价值=无
'版本 2(不起作用!)
mydate = If(dtReader.IsDBNull(dtReader.GetOrdinal("mydate")), Nothing, dtReader.GetDateTime(dtReader.GetOrdinal("mydate")))
值=#12:00:00#
谁能解释一下为什么版本 2 会得到这个值?
开启严格选项!正在进行隐式转换。
示例请参见 this 答案。
更新: 如果您设置的类型不可为空,这两个 if 语句 完全相同 。如果它们可以为空(默认情况下 DateTime 不是),则两个 if 语句会产生不同的结果。示例:
测试 1:
代码:
Dim d As DateTime?
d = If(True, Nothing, Now)
结果:
DateTime? dateTime = new DateTime?(DateTime.MinValue);
测试 2:
代码:
Dim d As DateTime?
If True Then
d = Nothing
Else
d = Now
End If
结果:
DateTime? dateTime = null;
这归结为编译器必须对 If
进行类型分析。请记住 Nothing
与 C# 的 null 不同,它更接近于 default(T)
:
If a variable is of a value type that is not nullable, assigning Nothing to it sets it to the default value for its declared type
现在,当编译器分析 If
时,它必须决定整个表达式的类型。这是它正在查看的内容:
If(Boolean,<AnyType>,DateTime)
现在,它必须根据第二个和第三个参数的类型来决定表达式的类型,并且必须从现有的类型中选择一种。因此,很自然地,它会选择 DateTime
。 Nothing
转换为 DateTime
与最小值相同。
要更改此设置,请为其提供 选择 以将类型推断为 DateTime?
:
mydate = If(dtReader.IsDBNull(dtReader.GetOrdinal("mydate")), _
CType(Nothing,DateTime?), _
dtReader.GetDateTime(dtReader.GetOrdinal("mydate")))
根据 Visual Basic Language Specification,第 11.22 节(条件表达式):
If three operands are provided, all three expressions must be classified as values, and the first operand must be a Boolean expression. If the result is of the expression is true, then the second expression will be the result of the operator, otherwise the third expression will be the result of the operator. The result type of the expression is the dominant type between the types of the second and third expression. If there is no dominant type, then a compile-time error occurs.
(我的重点)。
请注意,没有关于 "if this is being used in an assignment statement, you may also take into account the declared type of the variable being assigned" 的条件文本。