C#委託,事件理解入門

來源:互聯網
上載者:User
目錄

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所登記註冊,如果你調用 sd,SomeFunction 這個函數也會被調用,記住:我所說 SomeFunction的含義,後面,我們會用到它。

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

事件的理解

我們知道,在C#中:

l 按鈕(Button)就是一個類,當我們單擊它時,就觸發一次click事件。

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


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

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

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

public event NumberReachedEventHandler NumberReached;



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

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

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

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

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

public class NumberReachedEventArgs : EventArgs

{

private int _reached;

public NumberReachedEventArgs(int num)

{

this._reached = num;

}

public int ReachedNumber

{

get

{

return _reached;

}

}

}

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

namespace Events

{

public delegate void NumberReachedEventHandler(object sender,

NumberReachedEventArgs e);



/// <summary>

/// Summary description for Counter.

/// </summary>

public class Counter

{

public event NumberReachedEventHandler NumberReached;



public Counter()

{

//

// TODO: Add constructor logic here

//

}

public void CountTo(int countTo, int reachableNum)

{

if(countTo < reachableNum)

throw new ArgumentException(

"reachableNum should be less than countTo");

for(int ctr=0;ctr<=countTo;ctr++)

{

if(ctr == reachableNum)

{

NumberReachedEventArgs e = new NumberReachedEventArgs(

reachableNum);

OnNumberReached(e);

return;//don't count any more

}

}

}



protected virtual void OnNumberReached(NumberReachedEventArgs e)

{

if(NumberReached != null)

{

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

}

}

}

在Counter中,如果到達指定的時間點,就觸發一次事件,有以下幾個方面需要注意:

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);

//OnNumberReached(e);

if(NumberReached != null)

{

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

}

return;//don't count any more

}

這個問題問得很好,那就讓我們再看一下OnNumberReached 簽名:

protected virtual void OnNumberReached(NumberReachedEventArgs e)

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

②關鍵字 virtual 表明了 在繼承類中可以重寫該方法。

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



protected override void OnNumberReached(NumberReachedEventArgs e)

{

//Do additional work

base.OnNumberReached(e);

}

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

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

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



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




下面是btnRun的click事件:

private void btnRun_Click(object sender, System.EventArgs e)

{

if(txtCountTo.Text == "" || txtReachable.Text=="")

return;

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

}



private void oCounter_NumberReached(object sender, NumberReachedEventArgs e)

{

MessageBox.Show("Reached: " + e.ReachedNumber.ToString());

}



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

oCounter = new Counter();

oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached);



現在你明白了你剛才所做的一切,僅僅初始化 NumberReachedEventHandler 委託類型的對象(就像你執行個體化其他對象一樣),注意到 oCounter_NumberReached 方法的簽名與我前面提到的相似。

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

和oCounter_NumberReached一樣具有相同簽名的函數oCounter_NumberReached2,這兩個函數都可以被引用:



oCounter = new Counter();

oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached);

oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached2);

現在,觸發一個事件後,上面兩個函數被依次調用。



視情況而定,如果你想讓oCounter_NumberReached2在NumberReached事件發生後不再被調用,可以簡單地這樣寫:oCounter.NumberReached -= new NumberReachedEventHandler(oCounter_NumberReached2);



最後 讓我們看一下完整的原始碼,以供參考:


Form1.cs


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace Events
{
/**//// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
Counter oCounter = null;

private System.Windows.Forms.Button cmdRun;
private System.Windows.Forms.TextBox txtReachable;
private System.Windows.Forms.TextBox txtCountTo;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button btnRemoveDelegate;
/**//// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
oCounter = new Counter();
oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached);
oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached2);
}

/**//// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

Windows Form Designer generated code#region Windows Form Designer generated code
/**//// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmdRun = new System.Windows.Forms.Button();
this.txtReachable = new System.Windows.Forms.TextBox();
this.txtCountTo = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.btnRemoveDelegate = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// cmdRun
//
this.cmdRun.Location = new System.Drawing.Point(16, 72);
this.cmdRun.Name = "cmdRun";
this.cmdRun.Size = new System.Drawing.Size(48, 23);
this.cmdRun.TabIndex = 2;
this.cmdRun.Text = "Run";
this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click);
//
// txtReachable
//
this.txtReachable.Location = new System.Drawing.Point(144, 40);
this.txtReachable.Name = "txtReachable";
this.txtReachable.Size = new System.Drawing.Size(56, 20);
this.txtReachable.TabIndex = 1;
this.txtReachable.Text = "";
//
// txtCountTo
//
this.txtCountTo.Location = new System.Drawing.Point(144, 16);
this.txtCountTo.Name = "txtCountTo";
this.txtCountTo.Size = new System.Drawing.Size(56, 20);
this.txtCountTo.TabIndex = 0;
this.txtCountTo.Text = "";
//
// label1
//
this.label1.AutoSize = true;
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 = "Count To";
//
// label2
//
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 = "Reach this number";
//
// btnRemoveDelegate
//
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 = "Remove second handler";
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[] {
this.btnRemoveDelegate,
this.label2,
this.label1,
this.txtCountTo,
this.txtReachable,
this.cmdRun});
this.Name = "Form1";
this.Text = "Events";
this.ResumeLayout(false);

}
#endregion

/**//// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void btnRun_Click(object sender, System.EventArgs e)
{
if(txtCountTo.Text == "" || txtReachable.Text=="")
return;
oCounter.CountTo(Convert.ToInt32(txtCountTo.Text), Convert.ToInt32(txtReachable.Text));
}

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

private void btnRemoveDelegate_Click(object sender, System.EventArgs e)
{
oCounter.NumberReached -= new NumberReachedEventHandler(oCounter_NumberReached2);
oCounter.CountTo(Convert.ToInt32(txtCountTo.Text), Convert.ToInt32(txtReachable.Text));
}
}
}







Counter.cs




using System;

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

/**//// <summary>
/// Summary description for Counter.
/// </summary>
public class Counter
{
public event NumberReachedEventHandler NumberReached;

public Counter()
{
//
// TODO: Add constructor logic here
//
}
public void CountTo(int countTo, int reachableNum)
{
if(countTo < reachableNum)
throw new ArgumentException("reachableNum should be less than countTo");
for(int ctr=0;ctr<=countTo;ctr++)
{
if(ctr == reachableNum)
{
NumberReachedEventArgs e = new NumberReachedEventArgs(reachableNum);
OnNumberReached(e);
return;//don't count any more
}
}
}

protected virtual void OnNumberReached(NumberReachedEventArgs e)
{
if(NumberReached!=null)
{
NumberReached(this, e);
}
}
}

public class NumberReachedEventArgs : EventArgs
{
private int _reached;
public NumberReachedEventArgs(int num)
{
this._reached = num;
}
public int ReachedNumber
{
get
{
return _reached;
}
}
}
}

以上就是C#委託,事件理解入門的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 相關文章

    聯繫我們

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