C#基礎之泛型委派執行個體教程

來源:互聯網
上載者:User

標籤:視窗   too   www   style   思想   對象   介面   完全   color   

本文執行個體講述了C#中泛型委派的用法,並以樣本形式較為詳細的進行了用法分析。分享給大家供大家參考之用。具體如下:

首先,泛型委派是委託的一種特殊形式,雖然感覺看上去比較怪異,其實在使用的時候跟委託差不多,不過泛型委派更具有類型通用性。

就拿C#裡最常見的委託EventHandler打比方。在.NET 2.0以前,也就是泛型出現以前,普通的事件處理函數都由EventHandler定義,如下:

public delegate void EventHandler(object sender, EventArgs e);

EventHandler指代了這樣一類函數,這些函數沒有傳回值,並且有兩個參數,第一個參數是object類型,而第二個參數是EventArgs類型。

而.NET 2.0及其以後的版本,由於泛型的引入,所以一些內建(Built-in)的類、介面、委託都有了各自的泛型版本。EventHandler也不例外,它有了自己的泛型版本:EventHandler<T>,它的定義如下:

[Serializable]public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e) where TEventArgs: EventArgs;

您應該可以發現,第二個參數的類型由EventArgs變成了TEventArgs,而TEventArgs具體是什麼,則由調用方決定。假設IntEventArgs和StringEventArgs都繼承於System.EventArgs,那麼:

1.EventHandler<IntEventArgs>指代這樣一類函數:這些函數沒有傳回值,有兩個參數,第一個參數是object類型,第二個參數是IntEventArgs類型

2.EventHandler<StringEventArgs>指代這樣一類函數:這些函數沒有傳回值,有兩個參數,第一個參數是object類型,第二個參數是StringEventArgs類型

其實EventHandler<IntEventArgs>和EventHandler<StringEventArgs>是兩個完全不同的委託,它們所指代的函數都分別有著不同的簽名形式。請參見下面的樣本:

class IntEventArgs : System.EventArgs{  public int IntValue { get; set; }  public IntEventArgs() { }  public IntEventArgs(int value)  { this.IntValue = value; }}class StringEventArgs : System.EventArgs{  public string StringValue { get; set; }  public StringEventArgs() { }  public StringEventArgs(string value)  { this.StringValue = value; }}class Program{  static void PrintInt(object sender, IntEventArgs e)  {    Console.WriteLine(e.IntValue);  }  static void PrintString(object sender, StringEventArgs e)  {    Console.WriteLine(e.StringValue);  }  static void Main(string[] args)  {    EventHandler<IntEventArgs> ihandler = new EventHandler<IntEventArgs>(PrintInt);    EventHandler<StringEventArgs> shandler = new EventHandler<StringEventArgs>(PrintString);    ihandler(null, new IntEventArgs(100));    shandler(null, new StringEventArgs("Hello World"));  }}

有關泛型的具體特性與其在物件導向思想中的應用,本站有相關文章做了詳細解讀,感興趣的讀者可以查閱參考一下。

除聲明外, 跑步客文章均為原創,轉載請以連結形式標明本文地址
  C#基礎之泛型委派執行個體教程

本文地址:  http://www.paobuke.com/develop/c-develop/pbk23542.html






相關內容C#使用dir命令實現檔案搜尋功能樣本C#多線程與非同步區別詳解c++指標使用形參改變實參的方法C#動態對象(dynamic)詳解(實現方法和屬性的動態)
C#利用GDI繪製常見圖形和文字在winform下實現左右布局多視窗介面的方法使用C#代碼擷取預存程序傳回值C#中Arraylist的sort函數用法執行個體分析

C#基礎之泛型委派執行個體教程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.