国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#泛型實例詳解

2020-01-24 02:32:08
字體:
來源:轉載
供稿:網友

本文以實例形式講述了C#泛型的用法,有助于讀者深入理解C#泛型的原理,具體分析如下:

首先需要明白什么時候使用泛型:

當針對不同的數據類型,采用相似的邏輯算法,為了避免重復,可以考慮使用泛型。

一、針對類的泛型

針對不同類型的數組,寫一個針對數組的"冒泡排序"。

1.思路

● 針對類的泛型,泛型打在類旁。
● 由于在"冒泡排序"中需要對元素進行比較,所以泛型要約束成實現IComparable接口。

  class Program  {    static void Main(string[] args)    {      SortHelper<int> isorter = new SortHelper<int>();      int[] iarray = {8, 7, 1, 2, 12};      isorter.BubbleSort(iarray);      foreach (int item in iarray)      {        Console.Write(item+ ", ");      }      Console.ReadKey();    }  }   public class SortHelper<T> where T : IComparable  {    public void BubbleSort(T[] array)     {      int length = array.Length;      for (int i = 0; i <= length -2; i++)      {        for (int j = length - 1; j >= 1; j--)        {          if (array[j].CompareTo(array[j-1]) < 0)          {            T temp = array[j];            array[j] = array[j - 1];            array[j - 1] = temp;          }        }      }    }  } 

運行結果如下圖所示:

2.關于泛型約束

where T : IComparable 把T約束為實現IComparable接口
where T : class
where T : struct
where T : IComparable, new() 約束泛型必須有構造函數

3.關于冒泡算法

● 之所以for (int i = 0; i <= length -2; i++),這是邊界思維,比如有一個長度為5的數組,如果0號位元素最終調換到4號位,每次調一個位,需要經過4次才能到4號位,即for(int i = 0; i <= 5-2, i++),i依次為0, 1, 2, 4,期間經歷了4次。

● 至于for (int j = length - 1; j >= 1; j--)循環,即遍歷從最后一個元素開始到索引為1的元素,每次與前一個位置上的元素比較。

4.關于比較

int類型之所以能比較,是因為int類型也實現了IComparable接口。

byte類型也一樣實現了IComparable接口。

二、自定義一個類,使之也能實現冒泡算法

冒泡算法涉及到元素比較,所以自定義類必須實現IComparable接口。

  class Program  {    static void Main(string[] args)    {      Book[] bookArray = new Book[2];      Book book1 = new Book(100, "書一");      Book book2 = new Book(80, "書二");      bookArray[0] = book1;      bookArray[1] = book2;       Console.WriteLine("冒泡之前:");      foreach (Book b in bookArray)      {        Console.WriteLine("書名:{0},價格:{1}", b.Title, b.Price);      }       SortHelper<Book> sorter = new SortHelper<Book>();      sorter.BubbleSort(bookArray);      Console.WriteLine("冒泡之后:");      foreach (Book b in bookArray)      {        Console.WriteLine("書名:{0},價格:{1}", b.Title, b.Price);      }      Console.ReadKey();    }  }   public class SortHelper<T> where T : IComparable  {    public void BubbleSort(T[] array)     {      int length = array.Length;      for (int i = 0; i <= length -2; i++)      {        for (int j = length - 1; j >= 1; j--)        {          if (array[j].CompareTo(array[j-1]) < 0)          {            T temp = array[j];            array[j] = array[j - 1];            array[j - 1] = temp;          }        }      }    }  }   //自定義類實現IComparable接口  public class Book : IComparable  {    private int price;    private string title;     public Book(){}     public Book(int price, string title)    {      this.price = price;      this.title = title;    }     public int Price    {      get { return this.price; }    }     public string Title    {      get { return this.title; }    }     public int CompareTo(object obj)    {      Book book = (Book)obj;      return this.Price.CompareTo(book.Price);    }  }

運行結果如下圖所示:

三、針對方法的泛型

繼續上面的例子,自定義一個類,并定義泛型方法。

  //方法泛型  public class MethodSortHelper  {    public void BubbleSort<T>(T[] array) where T : IComparable    {      int length = array.Length;      for (int i = 0; i <= length - 2; i++)      {        for (int j = length - 1; j >= 1; j--)        {          if (array[j].CompareTo(array[j - 1]) < 0)          {            T temp = array[j];            array[j] = array[j - 1];            array[j - 1] = temp;          }        }      }    }  } 

主程序如下:

  class Program  {    static void Main(string[] args)    {      Book[] bookArray = new Book[2];      Book book1 = new Book(100, "書一");      Book book2 = new Book(80, "書二");      bookArray[0] = book1;      bookArray[1] = book2;       Console.WriteLine("冒泡之前:");      foreach (Book b in bookArray)      {        Console.WriteLine("書名:{0},價格:{1}", b.Title, b.Price);      }       MethodSortHelper sorter = new MethodSortHelper();      sorter.BubbleSort<Book>(bookArray);      Console.WriteLine("冒泡之后:");      foreach (Book b in bookArray)      {        Console.WriteLine("書名:{0},價格:{1}", b.Title, b.Price);      }      Console.ReadKey();    }  }   

運行結果如下圖所示:

另外,使用泛型方法的時候,除了按以下:

MethodSortHelper sorter = new MethodSortHelper(); sorter.BubbleSort<Book>(bookArray);

還可以這樣寫:  

      MethodSortHelper sorter = new MethodSortHelper();       sorter.BubbleSort(bookArray); 
     

可見,泛型方法可以根據數組實例隱式推斷泛型是否滿足條件。

四、泛型的其它優點

1.避免隱式裝箱和拆箱

以下包含隱式裝箱和拆箱:

ArrayList list = new ArrayList();for(int i = 0; i < 3; i++){  list.Add(i); //Add接收的參數類型是引用類型object,這里包含了隱式裝箱}for(int i = 0; i < 3; i++){  int value = (int)list[i]; //引用類型強轉成值類型,拆箱  Console.WriteLine(value);}

使用泛型避免隱式裝箱和拆箱:

List<int> list = new List<int>();for(int i = 0; i < 3; i++){  list.Add(i);}for(int i = 0; i < 3; i++){  int value = list[i];  Console.WriteLine(value);}

2.能在編譯期間及時發現錯誤

不使用泛型,在編譯期不會報錯的一個例子:

ArrayList list = new ArrayList();int i = 100;list.Add(i);string value = (string)list[0];

使用泛型,在編譯期及時發現錯誤:

List<int> list = new List<int>();int i = 100;list.Add(i);string value = (string)list[0];

五、使用泛型的技巧

1.在當前文件中給泛型取別名

using IntList = List<int>;IntList list = new IntList();list.Add(1);

2.在不同文件中使用泛型別名,定義一個類派生于泛型

public class IntList : List<int>{}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 丰县| 呼伦贝尔市| 镇康县| 法库县| 铜川市| 班玛县| 云梦县| 郓城县| 新巴尔虎左旗| 永新县| 黄山市| 清水县| 西乡县| 微山县| 外汇| 景德镇市| 开原市| 冀州市| 鹿泉市| 朝阳县| 容城县| 黎城县| 方正县| 大冶市| 星座| 临邑县| 定南县| 资兴市| 陆川县| 东莞市| 青岛市| 高邮市| 图们市| 蒙自县| 抚远县| 攀枝花市| 祁连县| 宁城县| 社旗县| 呼图壁县| 双牌县|