Why doesn't Array class expose its indexer directly?

前端 未结 9 1511
谎友^
谎友^ 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.

提交回复
热议问题