.net基礎掃盲-自訂泛型類

來源:互聯網
上載者:User

標籤:c#   自訂泛型類   

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)   {   }  }  

泛型的初始化:泛型是需要進行初始化的。使用Tdoc = 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;  }  

泛型代理(GenericDelegate):既然能夠定義泛型方法,自然也可以定義泛型代理

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屬性設定為不同的值,可以達到訪問不同段的目的。

.net基礎掃盲-自訂泛型類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.