可空类型,如果有问题 [英] Nullable type and if issue

查看:91
本文介绍了可空类型,如果有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是最简单的代码

Dim testInvoiceDate As DateTime? = If(String.IsNullOrEmpty(Nothing),
                                      Nothing,
                                      New DateTime(2018, 3, 20))

为什么变量 testInvoiceDate 不是 Nothing ,而是# 1/1/0001 12:00:00 AM#?!
太奇怪了!

Why variable testInvoiceDate is not Nothing , but #1/1/0001 12:00:00 AM# ?! That is very weird !

推荐答案

如果-两种情况下,语句将返回相同的数据类型。

因为在 False 情况下的返回类型为 DateTime ,因此返回类型是 True 情况的 DateTime -默认值。

The If-statement will return the same datatype for both cases.
Because the return-type in the False-case is DateTime, the return-type is the DateTime-default-value for the True-case.

DateTime 的默认值是 DateTime.MinValue ,它是#1/1 / 0001 12:00:00 AM#

这将按预期工作:

Dim testInvoiceDate As DateTime? = If(String.IsNullOrEmpty(Nothing),
                                      Nothing,
                                      New DateTime?(New Date(2018, 3, 20)))

这篇关于可空类型,如果有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆