gpt4 book ai didi

c# - 成员访问运算符 (.) 是否比空条件成员访问运算符 (?.) 具有更高的优先级?

转载 作者:行者123 更新时间:2023-12-04 01:26:16 25 4
gpt4 key购买 nike

我想我们都同意 C# 6.0 中引入的空条件成员访问运算符 ?. 非常方便。

但有一件事我一直想知道。给定以下代码:

using System.Collections.Generic;

public class MyClass
{
public void DoSomething(Foo foo)
{
var knownIndices = new[] { 42 };
bool overlaps;

// might throw a null reference exception
overlaps = foo.Indices.Overlaps(knownIndices);

// how I used to do it
overlaps = foo != null && foo.Indices != null && foo.Indices.Overlaps(knownIndices);

// with null conditional member access (won't compile)
//overlaps = foo?.Indices?.Overlaps(knownIndices).GetValueOrDefault();

// with null conditional member access (using local variable)
bool? overlapsOrIsIndeterminable = foo?.Indices?.Overlaps(knownIndices);
overlaps = overlapsOrIsIndeterminable.GetValueOrDefault();

// with null conditional member access (inlined)
overlaps = (foo?.Indices?.Overlaps(knownIndices)).GetValueOrDefault();

// with null conditional member access and null-coalescing
overlaps = foo?.Indices?.Overlaps(knownIndices) ?? false;
}

public class Foo
{
public HashSet<int> Indices;
}
}

为什么我必须在链式表达式中使用圆括号? ?.Overlaps() 清楚地评估为一个可为 null 的 bool 值,正如我们在使用局部变量的示例中看到的那样,因此我希望 .GetValueOrDefault() 是可编译的。

The C# language reference声明成员访问运算符 . 和空条件成员访问运算符 ?. 都是主要运算符,因此共享相同的优先级。

尽管语言引用中有说明,. 是否比 ?. 具有更高的优先级?

最佳答案

Does . despite of what is stated in the language reference have a higher precedence than ?.?

空条件运算符是一种特殊情况。正如 Dave 解释的那样,?. 右侧的任何连续表达式如果运算符左侧的表达式的计算结果为 null,则不计算该运算符.如果整个表达式的结果包含 ?.运算符通常会评估为原始值(例如 int ),它实际上会评估为 Nullable<int>值,但该值对于运算符的右侧可用。在运算符的右侧,您可以假设值不为空(这是空条件运算符的强大功能)。

同时 foo.GetIntValue()返回 int , foo?.GetIntValue()返回 Nullable<int> .如果附加到此表达式,则“目标”值的类型为 int , 不是 Nullable<int> .因此以下代码无法编译,因为 GetValueOrDefaultNullable<int> 的成员, 不属于 int .

foo?.GetIntValue().GetValueOrDefault(); // ERROR

因为整个 表达式的计算结果为 Nullable<int> , 添加括号确实可以让您调用 GetValueOrDefault .

(foo?.GetIntValue()).GetValueOrDefault();

请注意,您可以将此运算符与 null-coalescing operator 无缝组合

foo?.GetIntValue() ?? 1; // If foo is null, this expression will evaluate to 1

关于c# - 成员访问运算符 (.) 是否比空条件成员访问运算符 (?.) 具有更高的优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52536074/

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