需求:有ABC三个摸鱼的打工人,当收到输入“老板来了”时,提醒他们停止摸鱼,好好工作。
Delegate在搭载多个方法时,可以通过+=增加搭载的函数,也可以通过-=来去掉Delegate中的某个函数。
Program.cs
using System.Diagnostics;
using static System.Net.Mime.MediaTypeNames;
namespace Csharp委托
{
internal class Program
{
public delegate void 老板来了喊我一声委托();
static 老板来了喊我一声委托 喊一声;
//Delegate在搭载多个方法时,可以通过+=增加搭载的函数,也可以通过-=来去掉Delegate中的某个函数。
static void Main(string[] args)
{
摸鱼人 A = new 摸鱼人("A");
摸鱼人 B = new 摸鱼人("B");
摸鱼人 C = new 摸鱼人("C");
while (true)
{
string? s = Console.ReadLine();
if (s == null) continue;
if (s.Equals("老板来了"))
{
if (喊一声 != null)
{
喊一声();
}
}
}
}
public static void 添加委托(老板来了喊我一声委托 停止摸鱼)
{
喊一声 += 停止摸鱼;
}
}
}
摸鱼人.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Csharp委托
{
internal class 摸鱼人
{
string 名字;
public 摸鱼人(string 名字n)
{
名字 = 名字n;
Program.添加委托(停止摸鱼);
}
public void 停止摸鱼()
{
Console.WriteLine(名字+":停止摸鱼,好好工作!");
}
}
}
运行