gpt4 book ai didi

C#6 空条件运算符 - 作为代码切换器?

转载 作者:太空狗 更新时间:2023-10-30 00:49:19 24 4
gpt4 key购买 nike

我已经知道 null 条件运算符 can be used to test在执行成员访问之前为 null。

例如:

 int? length = customers?.Length; // null if customers is null 
Customer first = customers?[0];

如果 customerscustomers?.Length 中为 null,则 customers?.Length 将返回 null 而 null 将在 int 中?长度 = ... 变量

我也知道可以是used对于多线程环境中方法调用的单个原子操作:

public void OnFoo()
{
Foo?.Invoke(this, EventArgs.Empty);
}

但是

AFAIU - 如果 Foonull 那么

 Foo?.Invoke(this, EventArgs.Empty);

也是 null

所以我们剩下

public void OnFoo()
{
null; //compilation error
}

所以我问:

问题

似乎 null 条件运算符不仅用于测试 null,如果有,那么它会更深入:x?.y?.c?.d -

但它也像代码切换一样:

像这样:

  public void OnFoo()
{
Foo?.Invoke(this, EventArgs.Empty); //Let's assume Foo =null;
}

成为

  public void OnFoo()
{

}

我说的对吗?我没有找到这方面的任何文档。

最佳答案

空条件运算符是一个产生表达式的运算符 - 它不是语句

关于 Foo?.Invoke(this, EventArgs.Empty) 等同于 null 的逻辑并不成立,因为它似乎假设了一种“模板替换”不适用。

表达式的类型

Foo?.Invoke(this, EventArgs.Empty)

什么都不是,因为 Invoke 有一个 void 返回类型。你不能写:

// Invalid
var result = Foo?.Invoke(this, EventArgs.Empty);

这就像 C# 5 规范的 7.6.5 中一样:

The result of evaluating an invocation-expression is classified as follows:

  • If the invocation-expression invokes a method or delegate that returns void, the result is nothing. An expression that is classified as nothing is permitted only in the context of a statement-expression (§8.6) or as the body of a lambda-expression (§7.15). Otherwise a binding-time error occurs.
  • Otherwise, the result is a value of the type returned by the method or delegate.

成员调用可以使用空条件运算符,此时仅当主表达式的计算结果为非空值时才执行调用。涉及 null 条件运算符的调用表达式的结果与使用常规 . 运算符的结果相同,只是如果结果是不可为 null 的值类型,则结果为 null条件运算符是对应的可空值类型。

当然,当 C# 6 规范发布时,所有这些都会更准确地表达出来——但我不知道那会是什么时候。 (我认为目前没有 C# 6 规范。我确定 MS 内部有一个,但不是公开的。随着 ECMA 标准化进程越来越接近标准化 C# 5 ,这可能会影响 C# 6 的发布过程。)

关于C#6 空条件运算符 - 作为代码切换器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39074361/

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