Nullable类型疑问:为何DateTime?变量未取Nothing而是#1/1/0001 12:00:00 AM#?
问题解析:为什么你的Nullable DateTime得到的是MinValue而非Nothing?
这是个VB.NET里很容易踩的三元运算符类型推断坑!我来给你掰扯清楚原因和解决办法:
核心原因:If运算符的类型统一规则
VB的If(condition, truePart, falsePart)运算符会自动统一两个分支的返回类型。在你的代码里:
Dim testInvoiceDate As DateTime? = If(String.IsNullOrEmpty(Nothing), Nothing, New DateTime(2018, 3, 20))
右边的falsePart是New DateTime(...),属于值类型DateTime;而truePart的Nothing在没有明确类型的情况下,会被编译器推断为和falsePart同类型——也就是DateTime的默认值DateTime.MinValue(也就是你看到的#1/1/0001 12:00:00 AM#),而不是Nullable(Of DateTime)的null(也就是你预期的Nothing)。
最后这个DateTime.MinValue会被自动包装成DateTime?类型赋值给变量,但它本质上是一个有值的可空DateTime,而非null。
解决办法
这里有几种靠谱的修复方式:
1. 明确指定其中一个分支的类型为DateTime?
把falsePart转换成可空DateTime,让编译器把整个If表达式的类型推断为DateTime?:
Dim testInvoiceDate As DateTime? = If(String.IsNullOrEmpty(Nothing), Nothing, CType(New DateTime(2018, 3, 20), DateTime?))
或者直接用可空类型的构造器:
Dim testInvoiceDate As DateTime? = If(String.IsNullOrEmpty(Nothing), Nothing, New DateTime?(New DateTime(2018, 3, 20)))
2. 用传统的If...Then...Else语句赋值
绕开三元运算符的类型推断,直接给可空变量赋值:
Dim testInvoiceDate As DateTime? If String.IsNullOrEmpty(Nothing) Then testInvoiceDate = Nothing Else testInvoiceDate = New DateTime(2018, 3, 20) End If
3. 明确标记truePart的Nothing为DateTime?类型
用DirectCast强制指定Nothing的类型:
Dim testInvoiceDate As DateTime? = If(String.IsNullOrEmpty(Nothing), DirectCast(Nothing, DateTime?), New DateTime(2018, 3, 20))
这样就能让变量正确得到你预期的Nothing啦!
内容的提问来源于stack exchange,提问作者Disappointed
相关产品推荐
相关产品推荐

