委托/事件:猫叫鼠跑人醒
猫叫鼠跑人醒,这是一个很经典的 委托/事件 案例,本例中,猫类、鼠类、人类的基本属性不再累述,关键说一下 委托/事件。
第一步:因此在定义完毕 委托/事件 之后,要让猫叫触发定义的事件,
第二步:要给鼠对象、人对象订阅猫叫事件,以在猫叫触发事件时作出相应的反应。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CatCryRatRunMasterWake
{
/// <summary>
/// define a delegate
/// </summary>
public delegate void CatCryEventHandle();
class Program
{
static void Main(string[] args)
{
Cat cat = new Cat("Tom");
Rat rat = new Rat("Jack", cat);
Master master = new Master("Ls", cat);
cat.Cry();
Console.ReadKey();
}
}
/// <summary>
/// define a cat objects
/// </summary>
public class Cat
{
private string _name;
//define a cat cry event
public event CatCryEventHandle WhenCatCry;
public Cat(string name)
{
_name = name;
}
public void Cry()
{
this.WhenCatCry();
Console.WriteLine("猫叫!");
}
}
/// <summary>
/// define a rat objects
/// </summary>
public class Rat
{
private string _name;
public Rat(string name, Cat cat)
{
_name = name;
cat.WhenCatCry += Run; //订阅猫叫事件
}
public void Run()
{
Console.WriteLine("老鼠跑!");
}
}
/// <summary>
/// define a master objects
/// </summary>
public class Master
{
private string _name;
public Master(string name, Cat cat)
{
_name = name;
cat.WhenCatCry += WakeUp; //订阅猫叫事件
}
public void WakeUp()
{
Console.WriteLine("主人醒!");
}
}
}