如何避免在 foreach IList 之前进行空检查
How to avoid null checking before foreach IList
我有以下代码:
IList<object> testList = null;
...
if (testList != null) // <- how to get rid of this check?
{
foreach (var item in testList)
{
//Do stuff.
}
}
有没有办法避免 if
在foreach
之前?我看到了一些解决方案,但是当使用 List
时,使用 IList
时有什么解决方案吗?
试试这个
IList<object> items = null;
items?.ForEach(item =>
{
// ...
});
嗯,你可以试试??
运算符:
testList ?? Enumerable.Empty<object>()
我们要么得到 testList
本身,要么得到一个空的 IEnumerable<object>
:
IList<object> testList = null;
...
// Or ?? new object[0] - whatever empty collection implementing IEnumerable<object>
foreach (var item in testList ?? Enumerable.Empty<object>())
{
//Do stuff.
}
我从项目中窃取了以下扩展方法:
public static IEnumerable<T> NotNull<T>(this IEnumerable<T> list)
{
return list ?? Enumerable.Empty<T>();
}
然后这样使用方便
foreach (var item in myList.NotNull())
{
}
您可以像这样创建扩展方法:
public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
{
return source ?? Enumerable.Empty<T>().ToList();
}
那你可以这样写:
foreach (var item in testList.OrEmptyIfNull())
{
}
我有以下代码:
IList<object> testList = null;
...
if (testList != null) // <- how to get rid of this check?
{
foreach (var item in testList)
{
//Do stuff.
}
}
有没有办法避免 if
在foreach
之前?我看到了一些解决方案,但是当使用 List
时,使用 IList
时有什么解决方案吗?
试试这个
IList<object> items = null;
items?.ForEach(item =>
{
// ...
});
嗯,你可以试试??
运算符:
testList ?? Enumerable.Empty<object>()
我们要么得到 testList
本身,要么得到一个空的 IEnumerable<object>
:
IList<object> testList = null;
...
// Or ?? new object[0] - whatever empty collection implementing IEnumerable<object>
foreach (var item in testList ?? Enumerable.Empty<object>())
{
//Do stuff.
}
我从项目中窃取了以下扩展方法:
public static IEnumerable<T> NotNull<T>(this IEnumerable<T> list)
{
return list ?? Enumerable.Empty<T>();
}
然后这样使用方便
foreach (var item in myList.NotNull())
{
}
您可以像这样创建扩展方法:
public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
{
return source ?? Enumerable.Empty<T>().ToList();
}
那你可以这样写:
foreach (var item in testList.OrEmptyIfNull())
{
}