标签:
//定义委托
public delegate void QuestionEventHandler(string s);
//定义发布者
public class Publisher
{
public string Question = "太平洋的中间是什么?";
public event QuestionEventHandler QuestionEvent;//事件
public void Ask()
{
Console.WriteLine("提问"+Question);
//判断事件是否被注册
if(QuestionEvent != null)
{
QuestionEvent(Question);
}
}
}
//订阅者1
public class SubscriberA
{
public void OnQuestionAsked(string question)
{//判断条件
if(question == "太平洋的中间是什么?");
Console.WriteLine("甲:平");
else
Console.WriteLine("不知道");
}
}
//订阅者2
public class SubscriberB
{
public void OnQuestionAsked(string question)
{//判断
if(question == "太平洋的中间是什么?");
Console.WriteLine("乙:水");
else
Console.WriteLine("不知道");
}
}
//Main方法调用
class Program
{
static void Main(string[] args)
{
Publisher pub = new Publisher();
SubscriberA a = new SubscriberA();
SubscriberB b = new SubscriberB();
//注册事件
pub.QuestionEvent += a.OnQuestionAsked;
pub.QuestionEvent += b.OnQuestionAsked;
pub.Ask();
}
}
标签:
原文地址:http://www.cnblogs.com/gsj2ronger918/p/4515058.html