C#泛型實例詳解
本文以實例形式講述了C#泛型的用法,有助于讀者深入理解C#泛型的原理,具體分析如下:
首先需要明白什么時候使用泛型:
當針對不同的數(shù)據(jù)類型,采用相似的邏輯算法,為了避免重復,可以考慮使用泛型。
一、針對類的泛型
針對不同類型的數(shù)組,寫一個針對數(shù)組的"冒泡排序"。
1.思路
● 針對類的泛型,泛型打在類旁。
● 由于在"冒泡排序"中需要對元素進行比較,所以泛型要約束成實現(xiàn)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約束為實現(xiàn)IComparable接口
where T : class
where T : struct
where T : IComparable, new() 約束泛型必須有構造函數(shù)
3.關于冒泡算法
● 之所以for (int i = 0; i <= length -2; i++),這是邊界思維,比如有一個長度為5的數(shù)組,如果0號位元素最終調換到4號位,每次調一個位,需要經(jīng)過4次才能到4號位,即for(int i = 0; i <= 5-2, i++),i依次為0, 1, 2, 4,期間經(jīng)歷了4次。
● 至于for (int j = length - 1; j >= 1; j--)循環(huán),即遍歷從最后一個元素開始到索引為1的元素,每次與前一個位置上的元素比較。
4.關于比較
int類型之所以能比較,是因為int類型也實現(xiàn)了IComparable接口。
byte類型也一樣實現(xiàn)了IComparable接口。
二、自定義一個類,使之也能實現(xiàn)冒泡算法
冒泡算法涉及到元素比較,所以自定義類必須實現(xiàn)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; } } } } } //自定義類實現(xiàn)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); } }
運行結果如下圖所示:
三、針對方法的泛型
繼續(xù)上面的例子,自定義一個類,并定義泛型方法。
//方法泛型 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);
可見,泛型方法可以根據(jù)數(shù)組實例隱式推斷泛型是否滿足條件。
四、泛型的其它優(yōu)點
1.避免隱式裝箱和拆箱
以下包含隱式裝箱和拆箱:
ArrayList list = new ArrayList(); for(int i = 0; i < 3; i++) { list.Add(i); //Add接收的參數(shù)類型是引用類型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.能在編譯期間及時發(fā)現(xiàn)錯誤
不使用泛型,在編譯期不會報錯的一個例子:
ArrayList list = new ArrayList(); int i = 100; list.Add(i); string value = (string)list[0];
使用泛型,在編譯期及時發(fā)現(xiàn)錯誤:
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>{}
相關文章
C#實現(xiàn)將網(wǎng)址生成二維碼圖片方法介紹
這篇文章介紹了C#實現(xiàn)將網(wǎng)址生成二維碼圖片的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04DevExpress實現(xiàn)根據(jù)行,列索引來獲取RepositoryItem的方法
這篇文章主要介紹了DevExpress實現(xiàn)根據(jù)行,列索引來獲取RepositoryItem的方法,需要的朋友可以參考下2014-08-08讀寫XML文件的內容并將其顯示在ListView控件上的方法
下面小編就為大家?guī)硪黄x寫XML文件的內容并將其顯示在ListView控件上的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02Unity編輯器資源導入處理函數(shù)OnPreprocessAudio用法示例
這篇文章主要為大家介紹了Unity編輯器資源導入處理函數(shù)OnPreprocessAudio用法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08