C# 零合并与Lambdas
我的另一个问题没有编译,虽然表面上看起来应该(这不是同一个问题,我可以重写另一个答案来解决我的另一个问题) 给定C# 零合并与Lambdas,c#,C#,我的另一个问题没有编译,虽然表面上看起来应该(这不是同一个问题,我可以重写另一个答案来解决我的另一个问题) 给定 private Func<MyT, bool> SegmentFilter { get; set; } public MyConstructor(Func<MyT, bool> segmentFilter = null) { // This does not compile // Type or namespace mas could not
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;
}
}
private Func SegmentFilter{get;set;}
公共my构造函数(Func segmentFilter=null)
{
//这是不可编译的
//找不到类型或命名空间mas
分段过滤器=分段过滤器???(mas)=>{返回真;};
//这个(等价物?)表单编译得很好
if(segmentFilter==null)
{
分段过滤器=(mas)=>{return true;};
}
其他的
{
分段过滤器=分段过滤器;
}
}
为什么编译器在使用null合并运算符时遇到问题,而在语法为无糖的if/else版本时却没有遇到问题?这是因为
??
的优先级高于=>
。通过将lambda包装成()
,您可以轻松地解决此问题:
谢谢“另一个”答案也是你的。我对其进行了编辑以使其可编译;-)
SegmentFilter = segmentFilter ?? ((mas) => { return true; });