c#的事件機制範例程式碼: 貓-> 老鼠, 主人
來源:互聯網
上載者:User
using System;
namespace EventDemo
{
public delegate void CatBrayEventHandle(int score);
public class sleeping
{
public event CatBrayEventHandle CatShout;
int theScore;
public int Score
{
get {return theScore;}
set
{
if(theScore != value)
{
CatShout(value);
}
}
}
}
public class MouseRun
{
public MouseRun(sleeping slp)
{
slp.CatShout += new CatBrayEventHandle(slp_CatShout);
}
private void slp_CatShout(int score)
{
if(score > 100)
Console.WriteLine("老鼠: 有貓!快逃啊..");
else
Console.WriteLine("老鼠: 貓雖然叫了, 聲音不夠大, 赫赫, 老鼠沒聽見!");
}
}
public class Master
{
public Master(sleeping sleep)
{
sleep.CatShout += new CatBrayEventHandle(sleep_CatShout);
}
private void sleep_CatShout(int score)
{
if(score > 100)
Console.WriteLine("主人: 貓叫了!");
else
Console.WriteLine("主人: 貓雖然叫了, 聲音不夠大, 主人沒聽見!");
}
}
/**//// <summary>
/// Class1 的摘要說明。
/// </summary>
class Class1
{
/**//// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
sleeping slping = new sleeping();
MouseRun mr = new MouseRun(slping);
Master ms = new Master(slping);
//slping.Score = 66;
slping.Score = 123;
}
}
}