掌握C#自定義泛型類:從初始化說起
Generic是Framework 2.0的新元素,中文名字稱之為“泛型” ,特征是一個帶有尖括號的類,比如List< T>
C#自定義泛型類用得最廣泛,就是集合(Collection)中。實際上,泛型的產生其中一個原因就是為了解決原來集合類中元素的裝箱和拆箱問題(如果對裝箱和拆箱概念不明,請百度搜索)。由于泛型的使用,使得集合內所有元素都屬于同一類,這就把類型不同的隱患消滅在編譯階段——如果類型不對,則編譯錯誤。
這里只討論C#自定義泛型類。基本自定義如下:
- public class MyGeneric < T>
- ...{
- private T member;
- public void Method (T obj)
- ...{
- }
- }
這里,定義了一個泛型類,其中的T作為一個類,可以在定義的類中使用。當然,要定義多個泛型類,也沒有問題。
- public class MyGeneric < TKey, TValue>
- ...{
- private TKey key;
- private TValue value;
- public void Method (TKey k, TValue v)
- ...{
- }
- }
泛型的初始化:泛型是需要進行初始化的。使用T doc = default(T)以后,系統會自動為泛型進行初始化。
限制:如果我們知道,這個將要傳入的泛型類T,必定具有某些的屬性,那么我們就可以在MyGeneric< T>中使用T的這些屬性。這一點,是通過interface來實現的。
- // 先定義一個interface
- public interface IDocument
- ...{
- string Title ...{get;}
- string Content ...{get;}
- }
- // 讓范型類T實現這個interface
- public class MyGeneric < T>
- where T : IDocument
- ...{
- public void Method(T v)
- ...{
- Console.WriteLine(v.Title);
- }
- }
- // 傳入的類也必須實現interface
- public class Document : IDocument
- ...{
- ......
- }
- // 使用這個泛型
- MyGeneric< Document> doc = new MyGeneric< Document>();
泛型方法:我們同樣可以定義泛型的方法
- void Swap< T> (ref T x, ref T y)
- ...{
- T temp = x;
- x = y;
- y = temp;
- }
泛型代理(Generic Delegate):既然能夠定義泛型方法,自然也可以定義泛型代理
- public delegate void delegateSample < T> (ref T x, ref T y)
- private void Swap (ref T x, ref T y)
- ...{
- T temp = x;
- x = y;
- y = temp;
- }
- // 調用
- public void Run()
- ...{
- int i,j;
- i = 3;
- j = 5;
- delegateSample< int> sample = new delegateSample< int> (Swap);
- sample(i, j);
- }
設置可空值類型:一般來說,值類型的變量是非空的。但是,Nullable< T>可以解決這個問題。
- Nullable< int> x; // 這樣就設置了一個可空的整數變量x
- x = 4;
- x += 3;
- if (x.HasValue) // 使用HasValue屬性來檢查x是否為空
- ...{ Console.WriteLine ("x="+x.ToString());
- }
- x = null; // 可設空值
使用ArraySegment< T>來獲得數組的一部分。如果要使用一個數組的部分元素,直接使用ArraySegment來圈定不失為一個不錯的辦法。
- int[] arr = ...{1, 2, 3, 4, 5, 6, 7, 8, 9};
- // ***個參數是傳遞數組,第二個參數是起始段在數組內的偏移,第三個參數是要取連續多少個數
- ArraySegment< int> segment = new ArraySegment< int>(arr, 2, 3); // (array, offset, count)
- for (int i = segment.Offset; i< = segment.Offset + segment.Count; i++)
- ...{
- Console.WriteLine(segment.Array[i]); // 使用Array屬性來訪問傳遞的數組
- }
在例子中,通過將Offset屬性和Count屬性設置為不同的值,可以達到訪問不同段的目的。
以上就是C#自定義泛型類的用法介紹。
【編輯推薦】