Why doesn't Array class expose its indexer directly?

前端 未结 9 1467
谎友^
谎友^ 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:44

    I think one reason why Array doesn't implement that indexer directly is because all the specific array types (like char[]) derive from Array.

    What this means is that code like this would be legal:

    char[] array = new char[10];
    array[0] = new object();
    

    Code like this shouldn't be legal, because it's not type-safe. The following is legal and throws an exception:

    char[] array = new char[10];
    array.SetValue(new object(), 0);
    

    But SetValue() is not normally used, so this is not a big problem.

    0 讨论(0)
  • 2020-12-15 18:44

    C# Specs "12.1.1 The System.Array type" says, "Note that System.Array is not itself an array-type"

    Because it is not an array type.

    And note that "6.1.6 Implicit reference conversions" says, "From a single-dimensional array type S[] to System.Collections.Generic.IList and its base interfaces, provided that there is an implicit identity or reference conversion from S to T"

    C# Specs: http://www.microsoft.com/en-us/download/details.aspx?id=7029

    About why the indexer access is so much of a mystery, check this other SO post: implicit vs explicit interface implementation

    hope it helps.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题