【问题标题】:How to avoid null checking before foreach IList如何避免在 foreach IList 之前进行空值检查
【发布时间】:2020-03-16 01:42:33
【问题描述】:

我有以下代码:

IList<object> testList = null;

... 

if (testList != null) // <- how to get rid of this check?
{
   foreach (var item in testList)
   {
       //Do stuff.
   }
}

有没有办法避免ifforeach 之前?我看到了一些解决方案,但是在使用List时,使用IList时有什么解决方案吗?

【问题讨论】:

  • 你的意思是if(testList != null)
  • 确保 testList 已初始化。
  • foreach (var item in testList ?? new List&lt;object&gt;()) {...}
  • 你为什么在乎?如果有可能它可能为空,那么您需要检查。真的没什么大不了的。正如 Dmitry 所示,您可以通过初始化为一个空的对象列表来作弊,这意味着它不会循环,但对我来说,为了节省一行代码而在内存中初始化某些东西似乎毫无意义
  • fubo 是的,我的错。 DmitryBychenko 我认为这会起作用,谢谢!

标签: c# null-check


【解决方案1】:

你可以像这样创建扩展方法:

public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
 {
       return source ?? Enumerable.Empty<T>().ToList();
 }

然后你可以写:

 foreach (var item in testList.OrEmptyIfNull())
    {
    }

【讨论】:

    【解决方案2】:

    我从一个项目中窃取了以下扩展方法:

    public static IEnumerable<T> NotNull<T>(this IEnumerable<T> list)
    {
        return list ?? Enumerable.Empty<T>();
    }
    

    那就这样方便使用

    foreach (var item in myList.NotNull())
    {
    
    }
    

    【讨论】:

      【解决方案3】:

      嗯,你可以试试??运营商:

      testList ?? Enumerable.Empty<object>()
      

      我们要么得到testList 本身,要么得到一个空的IEnumerable&lt;object&gt;

      IList<object> testList = null;
      
      ...
      
      // Or ?? new object[0] - whatever empty collection implementing IEnumerable<object>
      foreach (var item in testList ?? Enumerable.Empty<object>())
      {
          //Do stuff.
      }
      

      【讨论】:

        【解决方案4】:

        试试这个

        IList<object> items = null;
        items?.ForEach(item =>
        {
          // ...
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-01
          • 1970-01-01
          • 2011-09-15
          • 1970-01-01
          相关资源
          最近更新 更多