上一节中讲到委托与事件,其实现在在实际用中不需再定义委托了 ,直接声明一个事件即可,前面之所以写出是为了能更清楚看清委托与事件关系.而且上面传递的参数有局限性只能是string类型,如果我们要是需要数值类型 那就得去改CatShoutEventArgs中代码,如果我们需要对象类型那还得再去改代码,这样比较麻烦 ,所以我们做出如下修改: 定义一个ObjectEventArgs<T>类 ,这里的T表示多态的意思 即表示什么类型都可以 这样我们以后只需要在声明事件时写入需要的类型就可以了;代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegate_Event_Demo
{
/// <summary>
/// 事件参数
/// </summary>
/// <typeparam name="T"></typeparam>
public class ObjectEventArgs<T> : EventArgs
{
private T _value;
public ObjectEventArgs(T pT)
{
this._value = pT;
}
public T Value
{
get { return this._value; }
}
}
}
Cat 修改如下 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace Delegate_Event_Demo
{
public class Cat
{
private string m_name = "";
public Cat(string pName)
{
this.m_name = pName;
}
public event EventHandler<ObjectEventArgs<string>> OnCatShoutEvent;
public void Shout()
{
MessageBox.Show("喵,我来了");
if (OnCatShoutEvent != null)
{
//为什么OnCatShoutEvent是无参数无返回值的呢?
//因为事件OnCatShoutEvent的类型是委托CatShoutEventHandler,而CatShoutEventHandler就是无参数无返回值的
OnCatShoutEvent(this, new ObjectEventArgs<string>(this.m_name));
}
}
}
}
Mouse修改如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace Delegate_Event_Demo
{
public class Mouse
{
private string m_name = "";
public Mouse(string pName)
{
this.m_name = pName;
}
public void Run(object sender, ObjectEventArgs<string> e)
{
MessageBox.Show("老猫" + e.Value + "来了," + this.m_name + "快跑");
}
}
}
MainWindow修改如下:
using System.Windows;
namespace Delegate_Event_Demo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Cat cat = new Cat("Tom");
cat.OnCatShoutEvent += new System.EventHandler<ObjectEventArgs<string>>(cat_OnCatShoutEvent);
cat.Shout();
}
void cat_OnCatShoutEvent(object sender, ObjectEventArgs<string> e)
{
Mouse mouse = new Mouse("jack");
mouse.Run(sender, e);
}
}
}
浙公网安备 33010602011771号