繁体   English   中英

可以使用空条件运算符(?。)对IEnumerable进行多次枚举

[英]Possible multiple enumeration of IEnumerable with null-conditional operator (?.)

我认为这是对reshaper的错误肯定,但我想征询其他人的意见。 也许我缺少了一些东西。

我在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触发警告,但是由于我做了ToList() ,所以这是不可能的,对吧?

如果我通过thisFooCanBeNull.SomeList?.ToList()更改thisFooCanBeNull?.SomeList?.ToList() ,它不会触发警告,但是由于“此foo可以为null”,所以我不想做更改。

有人看到此代码有问题吗?

我看不到应该多次枚举的情况。 我倾向于相信这是与仍然新颖的R有关的R#错误。 运算符,特别是因为将其替换为普通点运算符可以消除错误。

您可能想通过将断点或调试语句放在IEnumerable的任何源中来仔细检查它实际上并未多次枚举。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM