我没有找到让编译器推断EventHandler
参数类型的方法,但这是我的想法:
假设我们有一个服务(只是为了测试):
public class Service
{
public event EventHandler<MouseEventArgs> fooEvent1 = delegate { };
public event EventHandler<KeyEventArgs> fooEvent2 = delegate { };
public void Fire()
{
fooEvent1(null, null);
fooEvent2(null, null);
}
}
考虑这个通用类:
class Map<T> where T : EventArgs
{
Dictionary<string, EventHandler<T>> map;
public Map()
{
map = new Dictionary<string, EventHandler<T>>();
}
public EventHandler<T> this[string key]
{
get
{
return map[key];
}
set
{
map[key] = value;
}
}
}
它将 a 映射string
到 a EventHandler<T>
。显然,我们将针对不同的T
. 为了管理它们,让我们使用以下静态类:
static class Map
{
static Dictionary<Type, object> maps = new Dictionary<Type, object>();
public static Map<U> Get<U>() where U : EventArgs
{
Type t = typeof(U);
if (!maps.ContainsKey(t))
maps[t] = new Map<U>();
Map<U> map = (Map<U>)maps[t];
return map;
}
}
现在我们可以按如下方式使用它:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Map.Get<MouseEventArgs>()["1"] = Form1_fooEvent1;
Map.Get<KeyEventArgs>()["2"] = Form1_fooEvent2;
Service s = new Service();
s.fooEvent1 += Map.Get<MouseEventArgs>()["1"];
s.fooEvent2 += Map.Get<KeyEventArgs>()["2"];
s.Fire();
}
void Form1_fooEvent2(object sender, KeyEventArgs e)
{
textBox2.Text = "Form1_fooEvent2";
}
void Form1_fooEvent1(object sender, MouseEventArgs e)
{
textBox1.Text = "Form1_fooEvent1";
}
}