Как я могу наследовать от ArrayList <MyClass>? - PullRequest
6 голосов
/ 03 сентября 2010

Я хочу наследовать от некоторого класса массива / вектора / списка, чтобы я мог добавить к нему только один дополнительный специализированный метод .... что-то вроде этого:

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 голосов
/ 03 сентября 2010

ArrayList не является универсальным. Используйте List<Space> из System.Collections.Generic.

2 голосов
/ 11 сентября 2013

Вы можете создать оболочку вокруг 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; } }
}
2 голосов
/ 03 сентября 2010

Нет 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;
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...