委托和事件
#region
委托和事件
static
void
Main(
string
[] args)
{
ToolMan toolMan =
new
ToolMan(
"罗娴"
);
//工具人
LazyMan lazyMan1 =
new
LazyMan(
"张三"
);
//懒人
LazyMan lazyMan2 =
new
LazyMan(
"李四"
);
//懒人
LazyMan lazyMan3 =
new
LazyMan(
"王五"
);
//懒人
//多播委托
toolMan.DownStairD += lazyMan1.TakeFood;
//在下楼委托里加上张三拿外卖方法
toolMan.DownStairD += lazyMan2.TakePackage;
//在下楼委托里加上李四拿快递方法
toolMan.DownStairD += lazyMan3.TakeFood;
//在下楼委托里加上王五拿外卖方法
toolMan.DownStair();
//运行委托
}
internal
class
LazyMan
//懒人类
{
public
string
name;
//懒人姓名
public
LazyMan
(
string
name)
//生成构造函数
{
this
.name = name;
}
public
void
TakeFood()
//懒人拿外卖方法
{
Console.WriteLine(
$"给
{name}
拿外卖"
);
}
public
void
TakePackage()
//懒人拿快递方法
{
Console.WriteLine(
$"给
{name}
拿快递"
);
}
}
public
delegate
void
DownStairD
();
//创建一个下楼委托
internal
class
ToolMan
//工具人类
{
public
string
name;
//工具人姓名
public
ToolMan
(
string
name)
//生成构造函数
{
this
.name = name;
}
public
event
DownStairD DownStairD =
null
;
//声明下楼委托 在其中加入event事件 调用时不允许使用==只能+=或-=
public
void
DownStair()
//工具人下楼方法
{
Console.WriteLine(
$"工具人
{name}
下楼了"
);
if
(DownStairD !=
null
) DownStairD();
//下楼委托不为空的时候 调用下楼委托
}
}
#endregion