分类:
C Sharp
泛型:可以让多个类型共享一组代码,可以用不同的类型进行实例化。(写的比较抽象) C#中提供了5中泛型::类、结构、接口、委托、方法。前面4个是类型而方法是成员。 public class StackTool<T> { // 泛型数组 T[] StackArray; int StackPointer = 0; // 入栈 public void Push(T x) { if (!IsStackFull) StackArray[StackPointer++] = x; } public T Pop() { return (!IsStackEmpty) ? StackArray[--StackPointer] : StackArray[0]; } // 声明常量最大的栈数 const int MaxStack = 10; bool IsStackFull { get { return StackPointer >= MaxStack; } } bool IsStackEmpty { get { return StackPointer <= 0; } } // 无参构造数组 public StackTool() { StackArray = new T[MaxStack]; } public void Print() { for (int i = StackPointer - 1; i >= 0; i--) { Console.WriteLine(" Value:{0}", StackArray[i]); } } } // 主入口调用方法 static void Main(string[] args) { StackTool<int> StackInt = new StackTool<int>(); StackTool<string> StackString = new StackTool<string>(); StackInt.Push(3); StackInt.Push(6); StackInt.Push(7); StackInt.Push(9); StackInt.Push(10); StackInt.Print(); StackString.Push("This is fun"); StackString.Push("Hi There !"); StackString.Print(); } //输出结果 Value:10 Value:9 Value:7 Value:6 Value:3 Value:Hi There ! Value:This is fun 请按任意键继续. . .
评价