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