我正在使用數組實現一個通用堆棧。 但我得到的錯誤是:在c中使用數組實現通用堆棧#
不能申請用[]索引到類型的表達式 'T' 就行了
:
data[SP] = data;
如何解決這個問題?還我檢查此鏈接:
Cannot apply indexing to an expression of type 'T'
,我應該在這裏實現了相同的修復程序我的情況嗎?還是有其他最佳選擇?
這裏是我的代碼:
public class MyStack<T>
{
private T[] data { get; set; }
private int SP { get; set; }
private int Capacity { get; set; }
public MyStack(int capacity)
{
this.Capacity = capacity;
data = new T[Capacity];
SP = -1;
// it works here, dont know why??? ;)
data[0] = default(T);
}
public void Push(T data)
{
++SP;
if(SP>=Capacity) growArray();
// This is where i get error.
data[SP] = data;
}
public T Pop()
{
if (SP < 0) throw new InvalidOperationException();
T value = data[SP];
data[SP] = default(T);
SP--;
return value;
}
public T Peak()
{
if (SP < 0) throw new InvalidOperationException();
return data[SP];
}
private void growArray()
{
throw new NotImplementedException();
}
}
在此先感謝。
是否有你正在實施堆棧的具體原因?如果沒有,你可以使用['System.Collections.Generic.Stack'](http://msdn.microsoft.com/en-us/library/3278tedw.aspx) –
Waldfee