繁体   English   中英

Null Coalescence和Lambdas

[英]Null Coalescence and Lambdas

对我的另一个问题的这个答案没有编译,虽然表面上似乎应该(这不是同一个问题,我可以改写另一个答案为我的另一个问题工作)。

特定

private Func<MyT, bool> SegmentFilter { get; set; }

public MyConstructor(Func<MyT, bool> segmentFilter = null)
{
    // This does not compile
    // Type or namespace mas could not be found
    SegmentFilter = segmentFilter ?? (mas) => { return true; };

    // This (equivalent?) form compiles just fine
    if (segmentFilter == null) 
    {
        SegmentFilter = (mas) => { return true; };
    }
    else
    {
        SegmentFilter = segmentFilter;
    }
}

为什么编译器在使用null coalescent运算符时遇到了麻烦,但是没有使用syntax-sugar-free if / else版本?

那是因为?? 优先级高于=> 你可以通过将lambda包装成()来轻松解决这个问题:

SegmentFilter = segmentFilter ?? ((mas) => { return true; });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM