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;
}
}
}
を にマップstring
します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";
}
}