Stack 示例
本例说明我们现在可以使用 X# 创建泛型类!
在 Stack 类中,T 参数将在编译时被替换为一个类型。
/*
Stack 示例 - 作者:Robert van der Hulst:本例说明我们现在可以使用 X# 创建泛型类!注意:使用 /AZ 选项编译
*/
USING System.Collections.Generic
USING STATIC System.Console
FUNCTION Start AS VOID
LOCAL oStack AS Stack<INT>
LOCAL i AS LONG
TRY
oStack := Stack<INT>{25}
WriteLine("创建了一个包含 {0} 项的堆栈",oStack:Capacity)
WriteLine("Pushing 10 items")
FOR I := 1 TO 10
oStack:Push(i)
NEXT
WriteLine("弹出堆栈直至清空")
i := 0
WHILE oStack:Size > 0
i += 1
WriteLine(oStack:Pop())
END
WriteLine("从堆栈已弹出 {0} 项",i)
WriteLine("键入回车")
ReadLine()
WriteLine("下一行从空堆栈弹出并抛出异常")
ReadLine()
WriteLine(oStack:Pop())
CATCH e AS Exception
WriteLine("捕获到一个异常: {0}", e:Message)
END TRY
WriteLine("键入回车以退出")
ReadLine()
RETURN
CLASS Stack<T> WHERE T IS STRUCT, NEW()
PROTECT _Items AS T[]
PROTECT _Size AS INT
PROTECT _Capacity AS INT
PROPERTY Size AS INT GET _Size
PROPERTY Capacity AS INT GET _Capacity
CONSTRUCTOR()
SELF(100)
CONSTRUCTOR(nCapacity AS INT)
_Capacity := nCapacity
_Items := T[]{nCapacity}
_Size := 0
RETURN
PUBLIC METHOD Push( item AS T) AS VOID
IF _Size >= _Capacity
THROW StackOverFlowException{}
ENDIF
_Items[_Size] := item
_Size++
RETURN
PUBLIC METHOD Pop( ) AS T
_Size--
IF _Size >= 0
RETURN _Items[_Size]
ELSE
_Size := 0
THROW Exception{"不能从空堆栈弹出"}
ENDIF
END CLASS