gpt4 book ai didi

C# 6 空条件运算符不适用于 LINQ 查询

转载 作者:可可西里 更新时间:2023-11-01 03:10:43 25 4
gpt4 key购买 nike

我希望它能工作,但显然 IL 生成的方式会抛出 NullReferenceException。为什么编译器不能为查询生成类似的代码?

ThisWorks 情况下,编译器生成的代码将表达式的其余部分短路,为什么它不能对 LINQ 查询情况做同样的事情?

class Target
{
public ChildTarget Child;
}

class ChildTarget
{
public int[] Values;
}

IEnumerable<int> ThisWorks(Target target) =>
target.Child?.Values.Select(x => x);

IEnumerable<int> ThisDoesNotWork(Target target) =>
from x in target.Child?.Values select x;

ThisWorks(new Target());
ThisDoesNotWork(new Target()); // this throws NullReferenceException

反编译结果

private static IEnumerable<int> ThisDoesNotWork(Target target)
{
ChildTarget child = target.Child;
IEnumerable<int> values = (child != null) ? child.Values : null;
Func<int, int> func;
if ((func = Program._func) == null)
{
func = (Program._func = new Func<int, int>(Program._funcMethod));
}
return values.Select(func);
}

private static IEnumerable<int> ThisWorks(Target target)
{
ChildTarget child = target.Child;
IEnumerable<int> values;
if (child == null)
{
values = null;
}
else
{
IEnumerable<int> values = child.Values;
Func<int, int> func;
if ((func = Program._func2) == null)
{
func = (Program._func2= new Func<int, int>(Program._funcMethod2));
}
values = values.Select(func);
}
return values;
}

最佳答案

答案在 C# 语言规范中,它说

A query expression of the form

from x in e select x

翻译成

( e ) . Select ( x => x )

请注意最后一行 e 周围的括号。这清楚地表明 null 条件表达式(在您的示例中)在调用 Select 之前结束,这意味着 Select 可能会使用生成的 null 进行调用。

为什么它不能为 Linq 做同样的事情?因为这不是该功能设计的工作方式。空条件运算符的规范没有针对查询的特殊情况,反之亦然。

关于C# 6 空条件运算符不适用于 LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902097/

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