初学编程半年,在学到委托和事件的时候遇到不少困惑,尤其是在EventArgs自定义事件上,调用关系让人看得眼花缭乱,现在希望与大家分享我个人对自定义事件程序编码的理解,如有不足还请大家多多指正(~仅是个人理解哈)
在如下代码中出现“★”则代表曾经困惑到我的地方,在这些地方我将做一些个人见解性注释
在如下代码中出现“※”则代表现在还惑到我的地方,望大拿指点~
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Event
{
public class MsgEventArgs : EventArgs//※继承EventArgs类 目前还有点困惑我,如果不继承EventArgs程序也可以正常运行?
{
public string Message;
public MsgEventArgs(string msg)
{
this.Message = msg;
}
}
public class XinLang//新郎官对象
{
public delegate void QingTieEventHandler(Object sender, MsgEventArgs e);//创建委托 消息参数使用自定义的类 必须和调用方法参数列表相同
public event QingTieEventHandler QingTie;//创建事件
public void XinLangGuan(string msg)
{
if(QingTie!=null){
//Console.WriteLine(msg);★曾经认为在这个地方放置打印语句,将会输出3次“我要结婚了!都来啊!”这个语句。实际证明这个语句如果放在这里仅仅走一次
QingTie(this, new MsgEventArgs(msg));//★ this代表事件源 这里创建了一个MsgEventArgs对象(第一个类)并传入参数"我要结婚了!都来啊!" MsgEventArgs中的字段同时也被赋值
}
}
}
class Program
{
static void Main(string[] args)
{
XinLang xl = new XinLang();
Friend f1 = new Friend("老王");//创建朋友对象
Friend f2 = new Friend("老李");
Friend f3 = new Friend("老张");
xl.QingTie += new XinLang.QingTieEventHandler(f1.Message);//绑定事件
xl.QingTie += new XinLang.QingTieEventHandler(f2.Message);
xl.QingTie += new XinLang.QingTieEventHandler(f3.Message);
xl.XinLangGuan("我要结婚了!都来啊!");//传入参数
Console.ReadKey();
}
}
public class Friend//朋友类
{
public string Name;
public Friend(string name)
{
this.Name = name;//传入name赋值给Name 朋友名字
}
public void Message(Object sender, MsgEventArgs e)//★这里的e传入的是一个对象 通过分析e.Message得知e等同于本代码中的第一个类MsgEventArgs 而Message就是类中的一个字段
{
Console.WriteLine(e.Message);//★这里的e.Message调用的是上面第一个类中传入的参数“"我要结婚了!都来啊!"”
Console.WriteLine(Name+"收到,到时候准时参加");//朋友的响应
}
}
}