C#每日一課(三十三)

C#泛型
泛型Generic,允許延遲編寫類或方法中的編程元素的數據類型的規範,直到實際在程序中使用的時候。
可以通過數據類型的替代參數編寫類或方法的規範。當編譯器遇到類的構造函數或方法的函數調用時,它會成生代碼來處理指定的數據類型。

  • 泛型類

使用Visual Studio新建C#控制檯應用程序chapter24_001
1.新建一個泛型數組類

//定義一個泛型類
    public class MyGenericArray<T>
    {
        //泛型數組成員變量
        private T[] array;
        private int size;
        //初始化泛型數組
        public MyGenericArray(int size)
        {
            array = new T[size + 1];
            this.size = size;
        }
        //返回泛型數組指定下標的元素值
        public T GetItem(int index)
        {
            return array[index];
        }
        //爲指定索引的泛型數組指定值
        public void SetItem(int index, T value)
        {
            try
            {
                array[index] = value;
            }
            catch (Exception e)
            {
                Console.WriteLine("指定索引數組元素賦值失敗!"); 
            }
            
        }
        //獲得數組元素的長度
        public int GetLength()
        {
            return this.size;
        }
    }

2.在Main方法中加入如下代碼進行測試

string pattern = "[1-9]+";
            int length = 0;
            while (true)
            {
                Console.WriteLine("輸入數組的長度:");
                string len = Console.ReadLine();
                if (Regex.IsMatch(len, pattern))
                {
                    length = Convert.ToInt32(len);
                    break;
                }
                else
                {
                    Console.WriteLine("ERROR:請輸入大於0的正整數!");
                    continue;
                }

            }
            //聲明一個字符串數組
            MyGenericArray<string> stringArray = new MyGenericArray<string>(length);
            //爲數組中的每一個元素賦值
            for (int i = 0; i < length; i++)
            {
                Console.Write("請輸入數組中索引爲{0}的字符串:", i);
                string tmp = Console.ReadLine();
                stringArray.SetItem(i, tmp);
            }
            //遍歷數組中元素
            for (int i = 0; i < length; i++)
            {
                Console.Write(stringArray.GetItem(i) + "  ");
            }
            Console.WriteLine();
            Console.ReadKey();

編譯運行結果如下:
運行結果

  • 泛型特點
    1.有助於最大限度地重用代碼、保護類型的安全以及提高性能
    2.可以創建泛型集合類,.NET框架類庫在System.Collection.Generic命名空間中包含了一些泛型集合類
    3.可以創建自己的泛型接口、泛型類、泛型方法、泛型事件和泛型委託
    4.可以對泛型類進行約束以訪問特定數據類型方法
    5.關於泛型數據類型中使用的類型信息可在運行時通過使用反射獲取

  • 泛型方法
    可以通過類型參數來聲泛型方法。
    使用Visual Studio新建C#控制檯應用程序chapter24_002
    1.在項目中添加如下泛型方法

static void Swap<T>(ref T lhs, ref T rhs)
{
      System.Reflection.MemberInfo type = typeof(T);
      Console.WriteLine("當前調用使用類型:{0}",type.Name);
      T temp;
      temp = lhs;
      lhs = rhs;
      rhs = temp;
}

2.在Main方法中添加如下代碼進行測試

int a = 1;
int b = 2;

string c = "xiaoxie";
string d = "xiesheng";

Console.WriteLine("調用前a,b,c,d的值分別是:{0}、{1}、{2}、{3}", a, b, c, d);
Swap<int>(ref a, ref b);
Swap<string>(ref c, ref d);
Console.WriteLine("調用後a,b,c,d的值分別是:{0}、{1}、{2}、{3}", a, b, c, d);
Console.ReadKey();

編譯運行結果如下:
運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章