C# 泛型 簡單應用

using System;
using System.Collections.Generic;
using System.Text;

namespace DicrionaryTest
{
    public class Stack<T>//定義一個泛型類
    {
        private int count;//元素個數
        private T[] items;//用T替換一個具體的數據類型
        public Stack(int size)
        {

            items = new T[size];//使用泛型
            count = 0;
        }

        public void Push(T k)
        {
            items[count++] = k;
        }

        public T Pop()//採用泛型作爲類型
        {
            return items[--count];

        }

        public int Count//只讀屬性
        {
            get
            {
                return this.count;
            }
        }
    }

    class Test
    {
        static void Main(string[] args)
        {
            Stack<int> ts = new Stack<int>(10);//定義一個存放int型數據的棧
            ts.Push(123);//進棧
            ts.Push(456);
            string str = "";
            while (ts.Count > 0)
            {
                str = str + ts.Pop() + "\t";//出棧

            }
            Console.WriteLine(str);


            Console.ReadLine();
        }
    }
}

 

發佈了71 篇原創文章 · 獲贊 0 · 訪問量 4537
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章