gpt4 book ai didi

c# - 使用空条件运算符检查可能为空的对象的值

转载 作者:可可西里 更新时间:2023-11-01 02:59:55 25 4
gpt4 key购买 nike

我一直在玩 C# 6 的 Null 条件运算符 ( more info here )。

我真的很喜欢这种语法,我认为它使代码更具可读性,但是我认为当你检查一个对象的属性值时,代码到底要做什么是值得怀疑的,而这个对象本身可能为空。

例如,如果我有一个带有 decimal 属性的类,并且我想对该 decimal 的值进行条件检查,我会这样写:

if (foo?.Bar > max)
{
// do something
}

从表面上看,这看起来不错...如果 foo 不为空,则获取 Bar 的值并检查它是否大于最大值,如果是,则执行某些操作。

但是,如果 foo 为 null 怎么办?!

This documentation about the new and improved features of C# 6说了一些类似的话:

if in fact the value of the object is null, the null-conditional operator will return null. It short-circuits the call to Bar, and immediately returns null, avoiding the programming error that would otherwise result in a NullReferenceException.

我写了一个 fiddle here这表明它确实有效并且正在做我期望它做的事情但是我无法理解它如何决定条件的结果。

短路怎么等于假?在我的脑海中,这段代码现在会说“如果 foo 为 null,检查 null 是否 > max,这是不可能的,所以返回 false”或“如果 foo 为 null,则 foo != null 将返回 false,所以你得到false”但是文档说 null 条件检查返回 null,而不是 false。

最佳答案

How does the short-circuit equal a false?

if (foo?.Bar > max)
{
// do something
}

roughly equivalent到:

Decimal? bar = null;
if (foo != null)
bar = foo.Bar;

if (bar > max)
{
// do something
}

因此,短路不等于false。它等于 Decimal?(可为 null 的 Decimal),它是 thenmax 相比。

另请参阅:How does comparison operator works with null int?

关于c# - 使用空条件运算符检查可能为空的对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45796633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com