在c#中,使用包含null情况的Any()最干净的方法是什么?
本文关键字:是什么 方法 Any 包含 情况 null | 更新日期: 2023-09-27 18:10:14
我在c#中有以下代码:
if (this.Trucks.Any() || this.Cars.Any())
{
return true;
}
return false;
,但我刚刚意识到,有时一个或其中一个数组是空的,所以在我的情况下,我想null只是返回false(而不是抛出异常)。
我可以像这样添加前置空检查:
if ((this.Trucks != null && this.Trucks.Any()) ||
(this.Cars != null && this.Cars.Any()))
{
return true;
}
return false;
}
但是想看看有没有更简洁的方法
我建议您尽可能使用非空契约(空对象模式)。这意味着你将初始化可能在构造函数空数组(Enumerable.Empty<T>()
在IEnumerable
的情况下-在数组添加.ToArray()
的情况下)。null检查的问题是,它通常会在代码中扩散和增加——代码(和单元测试)的复杂性会不必要地增加。忘记在x
位置检查空比忘记在一个位置初始化空对象更容易。你也可以使用Code contracts
库在运行时检查你的"契约"。事实上,"null
"的发明者称之为十亿美元错误:"Null引用:十亿美元错误"
如果您想将空序列转换为空序列,则创建一个扩展方法:
public static class Seq
{
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> seq)
{
return seq ?? Enumerable.Empty<T>();
}
}
return this.Trucks.EmptyIfNull().Any() || this.Cars.EmptyIfNull().Any()
如果您不喜欢使用处理空值的扩展方法,您可以删除this
修饰符并使用
return Seq.EmptyIfNull(this.Trucks).Any() || Seq.EmptyIfNull(this.Cars).Any()
自己实现:
public static Class StaticHelpers
{
public static bool AnyEx<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null) return false;
return enumerable.Any();
}
}
像这样使用:
if (this.Trucks.AnyEx() || this.Cars.AnyEx())
{
return true;
}
return false;
在主if
条件中检查它们如何:
if ((this.Trucks != null && this.Trucks.Any()) ||
(this.Cars != null && this.Cars.Any()))
{
return true;
}
return false;
可以重写为一行:
return ((this.Trucks != null && this.Trucks.Any()) ||
(this.Cars != null && this.Cars.Any()));