首頁 後端開發 C#.Net教程 C#委託,事件理解入門

C#委託,事件理解入門

Dec 21, 2016 pm 02:54 PM

目錄 

l        導論 

l        什麼是委託 

l        事件的理解 

l        事件關鍵字 

l        最後 

  

導論 

    在學習C#中的委託和事件過程中,我讀了許多文章來理解他們二者究竟是怎麼一回事,以及如何使用他們,現在我將整個的理解過程陳述以下,我學到的每一方面,恐怕也是你們需要掌握的:-)。 

什麼是委託? 

    委託和事件這兩個概念是完全配合的。委託只是函數指針,那就是說,它能夠引用函數,透過傳遞位址的機製完成。委託是一個類,當你對它實例化時,要提供一個引用函數,將其作為它建構函數的參數。

  每一個委託都有自己的簽名,例如:Delegate int SomeDelegate(string s, bool b);是一個委託申明,在這裡,提及的簽名,就是說SomeDelegate 這個委託有string 和bool 類型的形參,傳回一個int 類型。 

上面提及的:當你對委託實例化時,要提供一個引用函數,將其作為它建構函數的參數。這裡要注意了:被引用的這個函數必須和委託有相同的簽名。

看下面的函數: 

PRivate int SomeFunction(string str, bool bln){...} 

你可以把這個函數傳給SomeDelegate的建構函數,因為他們有相似的簽章(in other Words,他們有類​​似的簽章都有相同的形參類型和個數,並且傳回相同的資料類型)。

    SomeDelegate sd = new SomeDelegate(SomeFunction); 

  sd 引用了SomeFunction,也就是說,SomeFunction已被呼叫所記得註冊,如果你使用sd,Someunctionsd 函式的意義,後面,我們會用到它。

  現在,你應該知道如何使用委託了,讓我們繼續理解事件之旅… 

事件的理解 

我們知道,在C#中: 

l      它時,就觸發一次click事件。 

l        時鐘(Timer)也是一個類,每過一毫秒,就觸發一次tick事件。


讓我們透過一個例子來學習,假定有這樣的情節: 

  現在有一個Counter的類,它有一個方法CountTo(int countTo, int reachableNum),該方法表示:在指定的時間段內( 0~~countTo),當到達指定的時間點reachableNum時,就觸發一次NumberReached事件。 

它還有一個事件:NumberReached,事件是委託類型的變數。意思是:如果為事件命名,用event關鍵字和要使用的委託類型申明它即可,如下所示: 

public event NumberReachedEventHandler NumberReached; 

  

在上面的申明中,NumberReached更確切的表示應該是:NumberReachedDelegate。但是微軟從不這樣認為MouseDelegate或PaintDelegate,,而是稱謂:MouseEventHandler 或 PaintEventHandler。所以 

NumberReachedEventHandler 比NumberReachedDelegate聽起來更方便一些,OK?好了,讓我們繼續,現在你知道了,在我們聲明事件之前,需要像下面這樣的形式來定義委託: 

public delegate void NumberReachedEventHandler(objected sender, NumberReachedEventArgs e); 

現在聲明的委託NumberReachedEventHandle,它有一個void 返回值,和object,NumberReachedEventArgs兩個形參。就像我們在第一節中強調的那樣,當實例化委託時,作為實參傳入的函數也必須擁有和委託同樣的簽名。 

在你的程式碼中, 你是否用過PaintEventArgs 或 MouseEventArgs來決定老鼠的移動位置?是否在觸發Paint事件的物件中用過Graphics 屬性?實際上,為使用者提供資料的類別都是繼承於System.EventArgs類,就是我們常說的事件參數類,如果事件不提供參數,就不定義該類。在我們的例子中,我們透過下面的類別提供預期的時間點。 

public class NumberReachedEventArgs : EventArgs 



    private int _reached; 

this._reached = num; 

    } 

    public int ReachedNumber 

    { 

        get 

        { 

            return _reached; 

        } 

    } 



好,有了前面的介紹,讓我們到Counter類別裡面看: 

namespace Events 



    public delegate void NumberReachedEventHandler(object sender, 🠎); 

    ///

 

    /// Summary description for Counter. 

    ///
 

    public class Counter 

    { 

        public event NumberReachedEventHandler NumberReached; 

        

        public Counter() 

        { 

            // 

            // TODO: Add constructor logic here 

// 

        } 

        public void CountTo(int countTo,      if(countTo
                throw new    "reachableNum should be less than countTo"); 

            for( int ctr=0;ctr
            { 

                   { 

                                  reachableNum); 

                      return ;//don't count any more 

                } 

            } 

        } 

  

        protected virtual void OnNumberReached(NumberReachedEventArgs e) 

        { 

            if(NumberReached != null) 

            { 

                NumberReached(this , e);//Raise the event 

            } 

        

l        則以呼叫NumberReached(它是NumberReachedEventHandler委託的實例)來完成一次觸發事件。 

NumberReached(this, e);  透過這種方式,可以呼叫所有的註冊函數。 

l        透過 NumberReachedEventArgs e = new NumberReachedEventArgs(reachableNum); 為所有的註冊函數提供事件資料。 

l        看了上面的程式碼,而你可能要問了:為什麼我們直接用 OnNumberReached(NumberReachedEventArgs e)方法來呼叫NumberReached(this,e),而不用下面的程式碼呢?

    if(ctr == reachableNum) 



    NumberReachedEventArgs e = new NumberReachedEventArgs(reachableNum);
    if(NumberReached != null) 

    { 

        NumberReached(this, e);//Raise the event 

    } 

    return;//don't count any more 

} at
virt 完結這個問題問得很好,那就再看一下這個問題
virt 問題🜎 OnNumberReached(NumberReachedEventArgs e) 

①你也明白關鍵字protected限定了只有從該類別繼承的類別才能呼叫該類別中的所有方法。 

②關鍵字 virtual 顯示了 在繼承類別中可以重寫該方法。 

這兩點非常有用,假設你在寫一個從Counter繼承而來的類,透過重寫OnNumberReached 方法,你可以在事件觸發之前,進行一次其他的工作。

  

protected override void OnNumberReached(NumberReachedEventArgs e) 



    //Do additional work 

    //Do additional work );


注意:如果你沒有呼叫base.OnNumberReached(e), 那麼從不會觸發這個事件!當你繼承該類別而想剔出它的一些其他事件時,使用該方式是非常有用的。 

l        也要注意到:委託 NumberReachedEventHandler 是在類別定義的外部,命名空間內定義的,對所有類別來說是可見的。 

好,該我們來實際操作使用Counter類別了。

  

在我們簡單的應用程式中,我們有兩個文字框,分別是:txtCountTo和txtReachable: 




下面是btnateRun的click事件: 
e) 

       { 

           if(txtCountTo.Text ; 

           oCounter.CountTo(Convert.ToInt32(txtCountTo.Text), Convert.ToInt32(txtReachable .Text)); 

       } 

  

private void oCounter_NumberReached(object s           MessageBox.Show("Reached: " + e.ReachedNumber.ToString()); 

   } 



初始化事件處理的語法如下: 

oCounter = new Counter(); 

          oCounter.NumberReached += new NumberReachedHandler(  oCounter.NumberReached += new NumberReachedHandler(    

現在你明白了你剛才所做的一切,只初始化NumberReachedEventHandler 委託類型的物件(就像你實例化其他物件一樣),注意到oCounter_NumberReached 方法的簽名與我前面提到的相似。 

也要注意我們用的是+= 而不是=;這是因為委託是特殊的對象,它可以引用多個對象(這裡是指它可以引用多個函數)。 For example 若有另一個 

與oCounter_NumberReached相同簽章的函數oCounter_NumberReached2,這兩個函數都可以引用: 

  
 .NumberReached += new NumberReachedEventHandler(oCounter_NumberReached) ; 

           oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached2); 

現在,觸發一個事件後,上面兩個函數依序呼叫。

  

視情況而定,如果你想讓oCounter_NumberReached2在NumberReached事件發生後不再被調用,可以簡單地這樣寫:oCounter.NumberReached -= new看一下完整的原始碼,以供參考: 


Form1.cs 


using System; 
using System.Drawing; 
using System.Collections 
using System.ComponModel. .Data; 

namespace Events 

    /**////  
    /// Form1 的摘要說明。
    /// 摘要> 
    公共類型Form1 :System.Windows.Forms.Form 
    { 
System.Windows.Forms.Button cmdRun; 
        私有System.Windows.Forms.TextBox txtReachable ; 
          System.Windows.Forms.TextBox txtCountTo; 
        私有System.Windows.         私有System.Windows.Forms.Button btnRemoveDelegate; 
        /**////  
       
        private System.ComponentModel.Container components = null ; 

        public Form1() 
        { 
       for Windows Form Designer support 
            // 
            
            // TODO: Add any constructor code after InitializeComponent call 
       = new Counter(); 
            oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached); 🠟umber (oCounter_NumberReached2); 
        } 

        /**//// any resources being used. 
        ///
 
        protec          if( disposing ) 
            { 
                 { 
                    
            } 
            base.Dispose( disposing ); 


        Windows 窗體設計器產生的程式碼#region Windows 表單設計器產生的程式碼 
        /**////        /** 器修改 
        /// 此方法的內容。
        /// 摘要> 
        private void InitializeComponent() 🎠  = new System.Windows.Forms.Button(); 
            this.txtReachable = new System.Windows.Forms.TextBox(); 🠎      .txtCountTo = new System.Windows.Forms.TextBox(); 
            this.label1 = new System.Windows.Forms.Label(); 
            this.btnRemoveDelegate = new System.Windows.Forms.Button(); 
            this.SuspendLayout(); 
       dRun 
            //  
            this.cmdRun  this .cmdRun.Name = "cmdRun"; 
            this.cmdRun.Size = new System.Drawing.Size(48, 23) 年輕
            this.cmdRun.Text = "運轉中"; 
            this .cmdRun.Click += new System.EventHandler(this.cmdRun_Click); 
            //       //  
            this.txtReachable.Location = new System.Drawing.Point(144, 40); 
. Name = "txtReachable"; 
            this.txtReachable.Size = new System.Drawing.Size(56, 20);             this.txtReachable.Text = ""; 
            //  txtCountTo 
            //  
            this.txt造成  this.txtCountTo.Name = "txtCountTo"; 
            this.txtCountTo.Size = new System.Drawing.Size(56, 20); 
            this.txtCountTo.TabIndex = 0; 
        
            // label1 
                           this.label1.Location = new System.Drawing.Point(16, 16); 
            this.label1.Name = "label1"; 
            this.label1.Size = new System.Drawing.Size(51, 13); 
            this.label1.TabIndex = 3; 
            this.label1.Text = "統計量為"; 
            //  
            /// label        this.label2.AutoSize = true; 
            this.label2.Location = new System.Drawing.Point(16, 40); 
            this.label2.Name = "label2"; 
            this.label2.Size = new System.Drawing.Size(99, 13); 
            this.label2.TabIndex = 4; 
            this.label2.Text = "達到這個數字"; 
            //  
            ///        this.btnRemoveDelegate.Location = new System.Drawing.Point(16, 104); 
            this.btnRemoveDelegate.Name = "btnRemoveDelegate"; 
            this.btnRemoveDelegate.Size = new System.Drawing.Size(168, 23); 
            this.btnRemoveDelegate.TabIndex = 5; 
            this.btnRemoveDelegate.Text = "刪除第二個處理程序"; 
            this.btnRemoveDelegate.Click += new System.EventHandler(this.btnRemoveDelegate_Click); 
            //  
            // Form1      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); 
            this.ClientSize = new System.Drawing.Size(224, 134); 
            this.Controls.AddRange(new System.Windows.Forms.Control[] { 
                                                                                 
                                                   這.label1,
this.txtCountTo, 
                                                                        this.txt可達, 
                                                                          this.cmdRun}); 
            this.Name = "Form1"; 
            this.Text = "事件"; 
            this.ResumeLayout(false); 

        } 
        #endregion

        /**//// ; 
        /// 應用程式的主要入口點。
        /// 摘要> 
        [STAThread] 
               Application.Run(new Form1()); 
        } 

        { 
if(txtCountTo.Text == "" || txtReachable.Text=="") 
                返回; 5To 2(txtReachable.Text)); 
        } 

private void oCounter_NumberReached(object sender, NumberReachedEventArgs e) 
        { 
            MessageBox.Show("已達到:" + e.ReachedNumber.ToString()); 
        } 
        private void oCounter_NumberReached2(object sender, NumberReachedEventArgs e) 
        { 
            MessageBox. Show("Reached2: " + e.ReachedNumber.ToString()); 
        } 

          { 
            oCounter.NumberReached -= new NumberReachedEventHandler(oCounter_NumberReached   (Convert.ToInt32(txtCountTo.Text), Convert.ToInt32(txtReachable.Text)); 
        } 
    


  

使用系統; 

命名空間事件

    public delegate void NumberReachedEventHandler(object sender, NumberReachedEventArgs e); 

    /**////  
    /// 計數器的摘要說明。
    /// 摘要> 
    公共類別Counter 
    { 
             public Counter() 
        { 
                       // 
        } 
        public void CountTo(int countTo, intreachableNum) 
        { 
            的ArgumentException ("reachableNum 應小於countTo"); 
            for(int ctr=0;ctr                { 
        um); 
                    OnNumberReached(e); 
                  } 
           } 
      eachedEventAr gs e)
        { 
            if(NumberReached!=null) 🎠            NumberReached(this, e); 
            } 
       Args 
    { 
        private int _reached; 
        this._reached = num; 
        } 
        public int ReachedNumber 🎠   
            { 
                  } 
    } 


 以上是C#委託,且事件瞭解入門的內容,相關內容請注意PHP中文網(www.php.cn)! 



本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

char在C語言字符串中的作用是什麼 char在C語言字符串中的作用是什麼 Apr 03, 2025 pm 03:15 PM

在 C 語言中,char 類型在字符串中用於:1. 存儲單個字符;2. 使用數組表示字符串並以 null 終止符結束;3. 通過字符串操作函數進行操作;4. 從鍵盤讀取或輸出字符串。

C語言各種符號的使用方法 C語言各種符號的使用方法 Apr 03, 2025 pm 04:48 PM

C 語言中符號的使用方法涵蓋算術、賦值、條件、邏輯、位運算符等。算術運算符用於基本數學運算,賦值運算符用於賦值和加減乘除賦值,條件運算符用於根據條件執行不同操作,邏輯運算符用於邏輯操作,位運算符用於位級操作,特殊常量用於表示空指針、文件結束標記和非數字值。

char在C語言中如何處理特殊字符 char在C語言中如何處理特殊字符 Apr 03, 2025 pm 03:18 PM

C語言中通過轉義序列處理特殊字符,如:\n表示換行符。 \t表示製表符。使用轉義序列或字符常量表示特殊字符,如char c = '\n'。注意,反斜杠需要轉義兩次。不同平台和編譯器可能有不同的轉義序列,請查閱文檔。

c#多線程和異步的區別 c#多線程和異步的區別 Apr 03, 2025 pm 02:57 PM

多線程和異步的區別在於,多線程同時執行多個線程,而異步在不阻塞當前線程的情況下執行操作。多線程用於計算密集型任務,而異步用於用戶交互操作。多線程的優勢是提高計算性能,異步的優勢是不阻塞 UI 線程。選擇多線程還是異步取決於任務性質:計算密集型任務使用多線程,與外部資源交互且需要保持 UI 響應的任務使用異步。

char與wchar_t在C語言中的區別 char與wchar_t在C語言中的區別 Apr 03, 2025 pm 03:09 PM

在 C 語言中,char 和 wchar_t 的主要區別在於字符編碼:char 使用 ASCII 或擴展 ASCII,wchar_t 使用 Unicode;char 佔用 1-2 個字節,wchar_t 佔用 2-4 個字節;char 適用於英語文本,wchar_t 適用於多語言文本;char 廣泛支持,wchar_t 依賴於編譯器和操作系統是否支持 Unicode;char 的字符範圍受限,wchar_t 的字符範圍更大,並使用專門的函數進行算術運算。

char在C語言中如何進行類型轉換 char在C語言中如何進行類型轉換 Apr 03, 2025 pm 03:21 PM

在 C 語言中,char 類型轉換可以通過:強制類型轉換:使用強制類型轉換符將一種類型的數據直接轉換為另一種類型。自動類型轉換:當一種類型的數據可以容納另一種類型的值時,編譯器自動進行轉換。

char和unsigned char的區別是什麼 char和unsigned char的區別是什麼 Apr 03, 2025 pm 03:36 PM

char 和 unsigned char 是存儲字符數據的兩種數據類型,主要區別在於處理負數和正數的方式:值範圍:char 有符號 (-128 到 127),unsigned char 無符號 (0 到 255)。負數處理:char 可以存儲負數,unsigned char 不能。位模式:char 最高位表示符號,unsigned char 無符號位。算術運算:char 和 unsigned char 作為有符號和無符號類型,其算術運算方式不同。兼容性:char 和 unsigned char

char數組在C語言中如何使用 char數組在C語言中如何使用 Apr 03, 2025 pm 03:24 PM

char 數組在 C 語言中存儲字符序列,聲明為 char array_name[size]。訪問元素通過下標運算符,元素以空終止符 '\0' 結尾,用於表示字符串終點。 C 語言提供多種字符串操作函數,如 strlen()、strcpy()、strcat() 和 strcmp()。

See all articles