Why does this string extension method not throw an exception?

前端 未结 3 1100
傲寒
傲寒 2020-12-12 19:50

I\'ve got a C# string extension method that should return an IEnumerable of all the indexes of a substring within a string. It works perfectly for it

3条回答
  •  失恋的感觉
    2020-12-12 20:36

    Enumerators, as the others have said, aren't evaluated until the time they start getting enumerated (i.e. the IEnumerable.GetNext method is called). Thus this

    List indexes = "a.b.c.d.e".AllIndexesOf(null).ToList();
    

    doesn't get evaluated until you start enumerating, i.e.

    foreach(int index in indexes)
    {
        // ArgumentNullException
    }
    

提交回复
热议问题