委托/事件:猫叫鼠跑人醒
Posted hanhan6494
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了委托/事件:猫叫鼠跑人醒相关的知识,希望对你有一定的参考价值。
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("主人醒!");
}
}
}
以上是关于委托/事件:猫叫鼠跑人醒的主要内容,如果未能解决你的问题,请参考以下文章