现用一个简单的工具人 来实现简单的事件+委托
不是很难,所以话不多说,直接上代码。
主要自己记录一下,方便以后回来看看
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate_Event
{
//定义委托
delegate void DownStairDelegate();
/// <summary>
/// 工具人类
/// </summary>
internal class ToolMan
{
public string Name { get; set; }
//event 事件是一种特殊的委托,或者说是受限制的委托,是委托的一种特殊应用,只能施加+=或者-=操作符。二者本质上是一个东西
public event DownStairDelegate DownStairDelegate = null;
public ToolMan(string name)
{
Name = name;
}
/// <summary>
/// 工具人调用委托
/// </summary>
public void DownStair()
{
Console.WriteLine("工具人"+Name+"下楼了");
if(DownStairDelegate!=null)
DownStairDelegate();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate_Event
{
public class LazyMan
{
public string Name { get; set; }
public LazyMan(string name)
{
Name = name;
}
public void TakeFood()
{
Console.WriteLine("给"+Name+"拿外卖");
}
public void TakePackage()
{
Console.WriteLine("给"+Name+"拿快递");
}
}
}
using System;
namespace Delegate_Event
{
internal class Program
{
static void Main(string[] args)
{
ToolMan tool = new ToolMan("小明");
LazyMan lazy1 = new LazyMan("张三");
LazyMan lazy2 = new LazyMan("李四");
LazyMan lazy3 = new LazyMan("王五");
tool.DownStairDelegate += lazy1.TakeFood;
tool.DownStairDelegate += lazy2.TakePackage;
tool.DownStairDelegate+=lazy3.TakeFood;
tool.DownStair();
tool.DownStairDelegate-=lazy3.TakeFood;
tool.DownStair();
Console.WriteLine("Hello World!");
}
}
}