使用空条件运算符(?。)可能多次枚举IEnumerable

时间:2015-11-10 16:03:06

标签: c# resharper null-conditional-operator

我认为这是来自resharper的假阳性,但我想得到别人的意见。也许我错过了什么。

我在Resharper 9.2和10中都发现了这种行为。

考虑这个课程:

   public class Foo
   {
      public IEnumerable<string> SomeList { get; set; }
   }

这个方法:

  public void Method(Foo thisFooCanBeNull)
  {
     List<string> theList = thisFooCanBeNull?.SomeList?.ToList();
     if (theList != null && theList.Count > 0) //Possible multiple enumeration of IEnumerable
     {
        foreach (string s in theList) //Possible multiple enumeration of IEnumerable
        {
           //Do something with list.
        }
     }
  }

theList.Countforeach会触发warnig,但由于我做了ToList(),这是不可能的,对吗?

如果我将thisFooCanBeNull?.SomeList?.ToList()更改为thisFooCanBeNull.SomeList?.ToList(),则不会触发警告,但由于“此foo可以为空”,所以我不想进行更改。

是否有人发现此代码存在问题?

1 个答案:

答案 0 :(得分:2)

我看不出这个应该多次枚举的情况。我倾向于认为这是一个与新手相关的R#bug?运算符,特别是因为交换普通点运算符会删除错误。

您可能希望通过在IEnumerable的任何源代码中放置断点或调试语句来仔细检查它实际上不会多次枚举。

相关问题