首頁 後端開發 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

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

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

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

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

熱門話題

Java教學
1666
14
CakePHP 教程
1425
52
Laravel 教程
1325
25
PHP教程
1272
29
C# 教程
1252
24
c#.net的持續相關性:查看當前用法 c#.net的持續相關性:查看當前用法 Apr 16, 2025 am 12:07 AM

C#.NET依然重要,因為它提供了強大的工具和庫,支持多種應用開發。 1)C#結合.NET框架,使開發高效便捷。 2)C#的類型安全和垃圾回收機制增強了其優勢。 3).NET提供跨平台運行環境和豐富的API,提升了開發靈活性。

從網絡到桌面:C#.NET的多功能性 從網絡到桌面:C#.NET的多功能性 Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#作為多功能.NET語言:應用程序和示例 C#作為多功能.NET語言:應用程序和示例 Apr 26, 2025 am 12:26 AM

C#在企業級應用、遊戲開發、移動應用和Web開發中均有廣泛應用。 1)在企業級應用中,C#常用於ASP.NETCore開發WebAPI。 2)在遊戲開發中,C#與Unity引擎結合,實現角色控制等功能。 3)C#支持多態性和異步編程,提高代碼靈活性和應用性能。

c#.net適合您嗎?評估其適用性 c#.net適合您嗎?評估其適用性 Apr 13, 2025 am 12:03 AM

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

C#.NET與未來:適應新技術 C#.NET與未來:適應新技術 Apr 14, 2025 am 12:06 AM

C#和.NET通過不斷的更新和優化,適應了新興技術的需求。 1)C#9.0和.NET5引入了記錄類型和性能優化。 2).NETCore增強了雲原生和容器化支持。 3)ASP.NETCore與現代Web技術集成。 4)ML.NET支持機器學習和人工智能。 5)異步編程和最佳實踐提升了性能。

.NET中的C#代碼:探索編程過程 .NET中的C#代碼:探索編程過程 Apr 12, 2025 am 12:02 AM

C#在.NET中的編程過程包括以下步驟:1)編寫C#代碼,2)編譯為中間語言(IL),3)由.NET運行時(CLR)執行。 C#在.NET中的優勢在於其現代化語法、強大的類型系統和與.NET框架的緊密集成,適用於從桌面應用到Web服務的各種開發場景。

將C#.NET應用程序部署到Azure/AWS:逐步指南 將C#.NET應用程序部署到Azure/AWS:逐步指南 Apr 23, 2025 am 12:06 AM

如何將C#.NET應用部署到Azure或AWS?答案是使用AzureAppService和AWSElasticBeanstalk。 1.在Azure上,使用AzureAppService和AzurePipelines自動化部署。 2.在AWS上,使用AmazonElasticBeanstalk和AWSLambda實現部署和無服務器計算。

C#和.NET運行時:它們如何一起工作 C#和.NET運行時:它們如何一起工作 Apr 19, 2025 am 12:04 AM

C#和.NET運行時緊密合作,賦予開發者高效、強大且跨平台的開發能力。 1)C#是一種類型安全且面向對象的編程語言,旨在與.NET框架無縫集成。 2).NET運行時管理C#代碼的執行,提供垃圾回收、類型安全等服務,確保高效和跨平台運行。

See all articles