首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C# 6 null条件运算符不适用于链接查询

C# 6 null条件运算符不适用于链接查询
EN

Stack Overflow用户
提问于 2016-03-10 04:39:20
回答 1查看 1.5K关注 0票数 17

我预计这会起作用,但很明显,IL生成的方式抛出了NullReferenceException。为什么编译器不能为查询生成类似的代码?

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

代码语言:javascript
复制
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

反编译的结果

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-10 10:14:08

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

表单的查询表达式

from x in e select x被翻译成

(E)。选择(x => x )

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

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

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35902097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档