I want to inherit from some kind of array/vector/list class so that I can add just one extra specialized method to it.... something like this:
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开发者_JAVA技巧;
}
}
}
But the compiler won't let me. Says
The non-generic type 'System.Collections.ArrayList' cannot be used with type arguments
How can I resolve this?
ArrayList
is not generic. Use List<Space>
from System.Collections.Generic.
There is no ArrayList<T>
. List<T>
works rather well instead.
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;
}
}
}
You can create a wrapper around ArrayList<T>
, which implements IReadOnlyList<T>
. Something like:
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; } }
}
精彩评论