我预计这会起作用,但很明显,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;
}
发布于 2016-03-10 10:14:08
答案就在C#语言规范中,它说
表单的查询表达式
from x in e select x被翻译成
(E)。选择(x => x )
请注意最后一行中e周围的圆括号。这清楚地表明null条件表达式(在您的示例中)在调用Select之前结束,这意味着可以使用结果null调用Select。
为什么它不能为Linq做同样的事情呢?因为这不是功能设计的工作方式。null条件运算符的规范没有查询的特殊情况,反之亦然。
https://stackoverflow.com/questions/35902097
复制相似问题