Why doesn't Array class expose its indexer directly?

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

    Even if array's were all 1D, you'd still have a Covariance and Contravariance issue:

    If the base class had a

    public Object this[int index] { get; set; }
    

    indexer property, then the concrete types indexer properties

    public TValue this[int index] { get; set; }
    

    would collide with that of the base type (since the parameter is of the setter is the same however the return value isn't).

    Casting the base class into either a base interface or a generic interface like either IList or IList solves this, since the non-specific indexer can be implemented explicitly. This is the same with the

    Add(Object value)
    

    vs.

    Add(TValue value)
    

    methods.

    The multi dimensional issue could, theoretically, be overcome by defining a conversion between 1D indexes and n-D indexes (e.g. [n] = [n / length(0), n % length(0)]) since n-D matrices are stored as one continuous buffer.

提交回复
热议问题