小问题,仅供理解:我有 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/