代码之家  ›  专栏  ›  技术社区  ›  mpen

如何从arraylist继承?

  •  6
  • mpen  · 技术社区  · 14 年前

    我想从某种类型的数组/向量/列表类继承,这样我就可以向它添加一个额外的专门化方法……像这样:

    public class SpacesArray : ArrayList<Space>
    {
        public Space this[Color c, int i]
        {
            get
            {
                return this[c == Color.White ? i : this.Count - i - 1];
            }
            set
            {
                this[c == Color.White ? i : this.Count - i - 1] = value;
            }
        }
    }
    

    但是编译器不允许我。说

    非泛型类型“System.Collections.ArrayList”不能与类型参数一起使用

    我如何解决这个问题?

    3 回复  |  直到 11 年前
        1
  •  11
  •   user180326    14 年前

    ArrayList 不是一般的。使用 List<Space> 来自System.Collections.Generic。

        2
  •  2
  •   Igor Zevaka    14 年前

    没有 ArrayList<T> . List<T> 相反,效果相当好。

    public class SpacesArray : List<Space>
    {
        public Space this[Color c, int i]
        {
            get
            {
                return this[c == Color.White ? i : this.Count - i - 1];
            }
            set
            {
                this[c == Color.White ? i : this.Count - i - 1] = value;
            }
        }
    }
    
        3
  •  2
  •   Erwin Mayer    11 年前

    您可以围绕 ArrayList<T> ,实现 IReadOnlyList<T> . 类似:

    public class FooImmutableArray<T> : IReadOnlyList<T> {
        private readonly T[] Structure;
    
        public static FooImmutableArray<T> Create(params T[] elements) {
            return new FooImmutableArray<T>(elements);
        }
    
        public static FooImmutableArray<T> Create(IEnumerable<T> elements) {
            return new FooImmutableArray<T>(elements);
        }
    
        public FooImmutableArray() {
            this.Structure = new T[0];
        }
    
        private FooImmutableArray(params T[] elements) {
            this.Structure = elements.ToArray();
        }
    
        private FooImmutableArray(IEnumerable<T> elements) {
            this.Structure = elements.ToArray();
        }
    
        public T this[int index] {
            get { return this.Structure[index]; }
        }
    
        public IEnumerator<T> GetEnumerator() {
            return this.Structure.AsEnumerable().GetEnumerator();
        }
    
        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }
    
        public int Count { get { return this.Structure.Length; } }
    
        public int Length { get { return this.Structure.Length; } }
    }