Why doesn't Array class expose its indexer directly?

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

    Array can't have an indexer because it needs to be able to represent an array with any number of dimensions. The indexer for a two dimensional array has a different signature than for a one dimensional array.

    If an indexer was provided and used on an Array that represented a two dimensional array what should happen?

    The solution that the language designers choose was to just not include an indexer at all.

    If you know that your ToArray method will always return a one dimensional array then consider using:

    public static T[] ToArray(this T source); 
    

    That will have an indexer.

    If the elements in the array will not all be of type T then you can return an object[]:

    public static object[] ToArray(this T source); 
    

提交回复
热议问题