C#事件处理的代理机制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public delegate void RingEvent(int ringKind);
public class SchoolRing
{
public RingEvent OnBellSound;
public void Jow(int ringKind)
{
if(ringKind==1||ringKind==2)
{
Console.Write(ringKind == 1 ? "上课铃声响了," : "下课铃声响了,");
{
if(OnBellSound!=null)
{
OnBellSound(ringKind);
}
}
}
else
{
Console.WriteLine("这个铃声参数不正确!");
}
}
}
public class Students
{
public void SubscribeToRing(SchoolRing sr)
{
sr.OnBellSound += SchoolJow;
}
public void SchoolJow(int ringKind)
{
if(ringKind==2)
{
Console.WriteLine("同学们开始课间休息!");
}
else if(ringKind==1)
{
Console.WriteLine("同学们开始认真学习!");
}
else
{
}
}
public void CancelSubscribe(SchoolRing sr)
{
sr.OnBellSound -= SchoolJow;
}
}
namespace Eventdelegate1
{
class Program
{
static void Main(string[] args)
{
SchoolRing sr = new SchoolRing();
Students st = new Students();
st.SubscribeToRing(sr);
Console.Write("请输入打铃参数(1:表示打上课铃;2:表示打下课铃):");
sr.Jow(Convert.ToInt32(Console.ReadLine()));
Console.Write("请输入打铃参数(1:表示打上课铃;2:表示打下课铃):");
sr.Jow(Convert.ToInt32(Console.ReadLine()));
Console.ReadLine();
}
}
}
本文地址:https://blog.csdn.net/vccodefan1/article/details/110150635