c# - ?可空类型的构造函数处理

标签 c# datetime nullable

小问题,仅供理解:我有 2 个可为 null 的日期时间。我读出了创建时间和更新时间,都可以填。所以我想检查一下哪个是以后的:

lastChangedIndrole = (tmpCreate > tmpUpdate ? tmpCreate : tmpUpdate);

但是这里发生了一些奇怪的事情。我希望在 f.e. 时抛出一个错误。 tmpUpdate 为 null,但它似乎返回了一些东西,但不是正确的值,而是第二个值,在我的示例中是更新。

有什么我不明白的吗?我认为代码会检查到 1900 的毫秒数,如果存在空值,则会引发错误。但这不会发生。这是我不明白的魔法吗?

附言: 有专门的词吗? vb中的IIF之类的构造函数?很难搜索到一些东西。

谢谢,这周有个好的开始

马蒂亚斯

最佳答案

读取 Nullable.Value 时,可空类型为 null 会抛出异常。但是它不会在比较时抛出异常,尽管它会给出意想不到的结果(将 null 与非 null 值进行比较永远不会返回 true)。

以下片段将说明问题

DateTime? dt1 = null;
DateTime? dt2 = DateTime.Now;

bool b1 = dt2 > dt1;//false(we expect true here)
bool b2 = dt2 < dt1;//false
bool b3 = dt2 == dt1;//false

此行为已记录 Here

When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for != (not equal). It is important not to assume that because a particular comparison returns false, the opposite case returns true. In the following example, 10 is not greater than, less than, nor equal to null. Only num1 != num2 evaluates to true.

关于c# - ?可空类型的构造函数处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18185879/

相关文章:

postgresql - 当开始时间戳的小时小于结束时间戳的小时时检索查询

sql-server - 在 SQL Server 中有效地添加列

c# - 类型或命名空间定义,或具有相同数量括号的文件结束预期错误

c# - 在 sql 和 web 应用程序之间发送安全密码的最佳实践?

sql - 获取时区时间之间的分钟差异

Java 检查 boolean 值是否为空

java - 空分析注释包之间有什么区别?

c# - LastOrDefault() 和 Last() 方法是否迭代列表的每个元素?

c# - 使用 RestSharp 反序列化 JSON 数组

javascript - 使用 javascript 将日期时间本地输入的值格式化为用户区域设置字符串