我急忙输入了以下代码:
List<Foo> myList = feedMyList();
var bar = myList.FirstOrDefault(x => something);
if (bar is null)
{
// something
}
我的第一个想法是我写错了,所以我体验了一点 C# 交互:
> var list = new List<string>();
> list.FirstOrDefault()
null
> list.FirstOrDefault() is null
true // As expected
> list.Add("abcdef");
> list.FirstOrDefault() is null
false // As expected
> list.FirstOrDefault(x => x.Length > 120) is null
true // As expected
一切都是正确的。编写(和使用)是否安全,if (bar is null)
还是我错过了潜在的问题?