Why doesn't Array class expose its indexer directly?

前端 未结 9 1510
谎友^
谎友^ 2020-12-15 18:10

something to mention for answering:

  1. Don\'t worry about variance, while the item in question is Array rather than

9条回答
  •  无人及你
    2020-12-15 18:48

    Short answer:

    System.Array is a base class for N-D arrays (not only 1-D), that's why 1-D indexer (object this[i]{get;set;}) cannot be a base member.

    Long answer:

    If you let's say create 2-dimensional array and try to access it's IList indexer:

    Array a;
    a=Array.CreateInstance(typeof(char), 1,1);
    (a as IList)[0]='a';
    

    You will get not supported exception.

    Good question would be:

    Why System.Array implement IList and IEnumerable while most of its implementation will throw NotSupportedException for non 1-D array??

    One more interesting thing to mention. Technically non of the arrays have class-indexer internally in classic meaning. Classic meaning of Indexer is a property "Item" + get(+set) method(s). If you go deep to reflection you will see that typeof(string[]) does not have indexer property and it only has 2 methods Get and Set - those method declared in string[] class (not in base class, unlike Array.SetValue, Array.GetValue) and they are used for compile-time indexing.

提交回复
热议问题