加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Null Coalescence和Lambdas

发布时间:2020-12-15 04:16:52 所属栏目:百科 来源:网络整理
导读:This answer到我的另一个问题没有编译,虽然从表面上看似乎应该(这不是同一个问题,我可以重写另一个答案为我的另一个问题工作). 特定 private FuncMyT,bool SegmentFilter { get; set; }public MyConstructor(FuncMyT,bool segmentFilter = null){ // This do
This answer到我的另一个问题没有编译,虽然从表面上看似乎应该(这不是同一个问题,我可以重写另一个答案为我的另一个问题工作).

特定

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; });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读