2010-09-03 16 views
6

voglio ereditare da un qualche tipo di matrice/vettore/classe di lista in modo che posso aggiungere solo un metodo specializzato in più ad esso .... qualcosa di simile:Come posso ereditare da ArrayList <MyClass>?

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; 
     } 
    } 
} 

Ma il compilatore non lasciare me. Dice

Il tipo non generico 'System.Collections.ArrayList' non può essere utilizzato con argomenti di tipo

Come posso risolvere questo?

risposta

11

ArrayList non è generico. Utilizzare List<Space> da System.Collections.Generic.

2

Non c'è ArrayList<T>. List<T> funziona piuttosto bene.

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; 
     } 
    } 
} 
+0

Sembra 'Elenco ' non funziona * abbastanza * come un array. Devi aggiungere degli elementi prima di poterli impostare ... 'this.AddRange (Enumerable.Repeat (Space.Empty, capacity))'. Oh bene, funziona abbastanza :) – mpen

2

È possibile creare un wrapper ArrayList<T>, che implementa IReadOnlyList<T>. Qualcosa di simile:

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; } } 
} 
Problemi correlati