簡體   English   中英

C#6 null條件運算符不適用於LINQ查詢

[英]C# 6 null conditional operator does not work for LINQ query

我希望這可以工作,但顯然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#語言規范中,它說

表單的查詢表達式

X電子選擇X

被翻譯成

e )。 選擇( x => x

注意最后一行中e周圍的括號。 這清楚地表明,在調用Select之前,null條件表達式(在您的示例中)結束,這意味着可能會使用結果null調用Select。

為什么它不能為Linq做同樣的事情? 因為這不是該功能的設計方式。 空條件運算符的規范沒有查詢的特殊情況,反之亦然。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM