委托delegate的简单示例,及关于event
委托的实例化存在于发布者类中,订阅与取消订阅都作为方法存在于类中,委托订阅的话,程序就按照两个类来设计,委托发布者和委托订阅者,适用于功能需求由两个即以上部分组成,其中的几个部分(订阅者)产生的结果依赖于另一个部分(发布者)的结果是什么。委托即绑定了几个部分里的相关方法,是两者之间的桥梁。
namespace ConsoleApplication3
{ //委托定义,委托的签名要和需要绑定的方法一致,主要是传入的参数个数和类型
public delegate void BellResponse(int ss);
//委托发布者
public class Bellring
{ //在发布者类中发布委托,
//**注意使用了event事件定义,对于委托进行了封装,无论前面的修饰符是什么,实质上都是private,外部程序调用+=和-+可以对事件进行方法的订阅**
public event BellResponse response;
//不同数字的输入对应的不同的铃声状态
public void ring_accd(int sign)
{
int BellRing = sign ;
string str_0 = "开始上课!";
string str_1 = "下课了!";
if (BellRing == 1 || BellRing == 2)
{
Console.WriteLine("{0}", BellRing == 1 ? str_0 : str_1);
//**这里有一个在订阅者成功订阅以后的回调,这样的话就可以在发布者类里直接调用订阅者的方法**
if (response != null) //**如果委托实例化的字段不为空,就表明已经订阅成功,即委托已经成功绑定方法**
{
response(sign);
}
}
else
{ //数字不是1也不是2
Console.WriteLine("铃声信号有误!");
}
}
}
//委托订阅者
public class Student
{
//一个类在另一个类中的实例化,注意位置,不要放在属性或者方法中
Bellring ring = new Bellring();
//订阅者类中订阅相应的委托
public void Subscribe(Bellring ring)
{ //注意在给委托赋值(订阅)的时候用+=比较好,因为可以在之后用-=解除,=不可以
ring.response += student_accd ;
}
public void student_accd (int sign)
{
int BellRing = sign;
if (BellRing == 1)
{
Console.WriteLine("请学生回到教室!");
}
else if(BellRing==2)
{
Console.WriteLine("自由活动!");
}
}
//取消订阅,对比委托的赋值(订阅)
public void Cancel(Bellring rr)
{
ring.response -= student_accd;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入数字:");
string i = Console.ReadLine();
int j = Convert.ToInt16(i);
Bellring bell = new Bellring();
Student ss= new Student ();
ss.Subscribe(bell);//**一定注意要执行委托的订阅,否则委托无效**
bell.ring_accd(j);
Console.ReadLine();
}
}
}