Why doesn't Array class expose its indexer directly?

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

    a as IList is (basically) casting. So just cast it first:

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

    Edit: the reason is: because the interface for Array simply doesn't define an indexer. It uses SetValue(Object, Int32) and Object GetValue(Int32). Notice the ominous Object stuff in there. Array isn't type specific; it's built for the lowest common denominator: Object. It could have just as easily defined an indexer, but in practice you'd still have the un/boxing problem.

提交回复
热议问题