?? 事件.txt
字號:
事件(event):在某些特定事情發生的時候通知其他對象。
為類型提供三種能力:
1.允許對象登記事件。
2.允許對象注銷事件。
3.允許定義事件對象維持一個登記的集合,并在某些特定事情發生時通知這些對象。
事件模型建在委托(delegate)機制上。
1.示例
using System;
namespace Movecont
{
class MailManager
{
//保存事件信息(可選)
public class MailMsgEventArgs:EventArgs
{
public MailMsgEventArgs(String from,String to,String Subject,String body)
{
this.from=from;
this.to=to;
this.subject=subject;
this.body=body;
}
public readonly String from,to,subject,body;
}
//方法原型(可選)
public delegate void MailMsgEventHandler(Object sender,MailMsgEventArgs args);
//事件成員(自動維護訂閱對象)
public event MailMsgEventHandler MailMsg;
//通知對象
protected virtual void OnMailMsg(MailMsgEventArgs e)
{
if(MailMsg!=null)
MailMsg(this,e);
}
//輸入轉化為事件
public void SimulateArrivingMsg(String from,String to,String subject,String body)
{
MailMsgEventArgs e=new MailMsgEventArgs(from,to,subject,body);
OnMailMsg(e);
}
}
class Fax
{
//訂閱事件
public Fax(MailManager mm)
{
//(使用了事件,委托,回調方法)
mm.MailMsg+=new MailManager.MailMsgEventHandler(FaxMsg);
}
//回調方法
private void FaxMsg(Object sender,MailManager.MailMsgEventArgs e)
{
Console.WriteLine("Faxing mail message:");
Console.WriteLine("From:{0}\n To:{1}\n Subject:{2}\n Body:{3}\n",e.from,e.to,e.subject,e.body);
}
//注銷事件
public void Unregister(MailManager mm)
{
MailManager.MailMsgEventHandler callback=new MailManager.MailMsgEventHandler(FaxMsg);
mm.MailMsg-=callback;
}
}
}
using System;
using System.Collections;
namespace Movecont
{
/// <summary>
/// 事件。
/// </summary>
class Class1
{
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
MailManager mymail=new MailManager();
Fax myfax=new Fax(mymail);
mymail.SimulateArrivingMsg("gelifeng","chi","Hi,beibei","Best regard!");
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -