Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

后端 未结 7 1172
长情又很酷
长情又很酷 2020-12-14 05:41

Is there any specific reason why indexing is not allowed in IEnumerable.

I found a workaround for the problem I had, but just curious to know why it does not allow i

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 06:04

    The []-operator is resolved to the access property this[sometype index], with implementation depending upon the Element-Collection.

    An Enumerable-Interface declares a blueprint of what a Collection should look like in the first place.

    Take this example to demonstrate the usefulness of clean Interface separation:

    var ienu = "13;37".Split(';').Select(int.Parse);
    //provides an WhereSelectArrayIterator
    var inta = "13;37".Split(';').Select(int.Parse).ToArray()[0];
    //>13
    //inta.GetType(): System.Int32
    

    Also look at the syntax of the []-operator:

      //example
    public class SomeCollection{
    public SomeCollection(){}
    
     private bool[] bools;
    
      public bool this[int index] {
         get {
            if ( index < 0 || index >= bools.Length ){
               //... Out of range index Exception
            }
            return bools[index];
         }
         set {
            bools[index] = value;
         }
      }
    //...
    }
    

提交回复
热议问题