Zac*_*ary 5 c# null null-conditional-operator
当方法属于所讨论的对象时,空条件运算符非常有用,但是如果所讨论的对象是参数怎么办?例如,这个可以缩短吗?
var someList = new List<SomeType>();
if (anotherList.Find(somePredicate) != null)
{
someList.Add(anotherList.Find(somePredicate))
}
Run Code Online (Sandbox Code Playgroud)
我想到的一个解决方案是使用如下扩展方法:
public static void AddTo<T>(this T item, List<T> list)
{
list.Add(item);
}
Run Code Online (Sandbox Code Playgroud)
这样,第一个代码块可以减少为:
var someList = new List<SomeType>();
anotherList.Find(somePredicate)?.AddTo(someList);
Run Code Online (Sandbox Code Playgroud)
但此解决方案特定于本示例(即,如果对象不为空,则将对象添加到列表中)。是否有通用方法来指示如果参数为 null,则不应运行该方法?
永远不要这样做
var someList = new List<SomeType>();
if (anotherList.Find(somePredicate) != null)
{
someList.Add(anotherList.Find(somePredicate))
}
Run Code Online (Sandbox Code Playgroud)
这将搜索列表两次,这是不必要的。使用临时变量代替。
var someList = new List<SomeType>();
var find = anotherList.Find(somePredicate);
if (find != null) someList.Add(find);
Run Code Online (Sandbox Code Playgroud)
是否有通用方法来指示如果参数为 null,则不应运行该方法?
目前还没有这样的功能。然而,还有其他替代方案可以更好地发挥作用,就像提供的其他答案一样。