问题描述
在昨天的讨论之后,我正在研究可以在应用程序范围内订阅的Singleton的"Notifier"类的想法.为了通过允许在事件args中传递任何类型来使其更有用,我认为泛型将是一个好主意.通用TEventArgs<T> : EventArgs被设置并且可以正常工作
单例的通用类是不可能的,因为这样实例将被绑定到单个类型,所以我得到了一个通用方法,该方法反过来调用
protected virtual void OnNotify<T>(TEventArgs<T> e) { }
因为类本身不是通用的,所以我无法弄清楚如何创建通用事件
public event EventHandler<TEventArgs<T>> Notification;
,因为T不是尚未定义.有办法吗?
是否失败?是否可以基于OnNotify方法中T的类型引发特定类型的事件,该事件具有硬编码类型(例如public event EventHandler<TEventArgs<int>> Notification)
并使用e参数?
我可能在这里吠叫了错误的树,但我确定应该可以!
After a discussion yesterday I''m playing around with the idea of a Singleton ''Notifier'' class that can be subscribed to application wide. To make this more useable by allowing any type to be passed in event args, I figured generics would be a good idea. The genric TEventArgs<T> : EventArgs is set up and working fine
A generic class for the singleton is not possible as then the instance would be tied to a single type so I''ve got a generic method that in turn calls
protected virtual void OnNotify<T>(TEventArgs<T> e) { }
Because the class itself isn''t generic, I can''t figure out how to create a generic event
public event EventHandler<TEventArgs<T>> Notification;
as T isn''t yet defined of course. Is there a way?
Failing that, is it possible to raise a specific event that has the type hard coded
(e.g. public event EventHandler<TEventArgs<int>> Notification)
based upon the type of T in the OnNotify method and use the e parameter?
I could be barking up the wrong tree here but I''m sure it should be possible!
推荐答案
<br /> class TEventArgs<T> : EventArgs { public T Value { get; set; } }<br /><br /> class Test<br /> {<br /> Dictionary<Type, object> d = new Dictionary<Type,object>();<br /><br /> public event EventHandler<TEventArgs<int>> MyEvent1<br /> {<br /> add<br /> {<br /> d.Add(typeof(int), value); <br /> }<br /><br /> remove<br /> {<br /> d.Remove(typeof(int));<br /> }<br /> }<br /><br /> public event EventHandler<TEventArgs<string>> MyEvent2<br /> {<br /> add<br /> {<br /> d.Add(typeof(string), value);<br /> }<br /><br /> remove<br /> {<br /> d.Remove(typeof(string));<br /> }<br /> }<br /><br /> public void OnNotify<T>(T t)<br /> {<br /> EventHandler<TEventArgs<T>> del = (EventHandler<TEventArgs<T>> ) d[t.GetType()];<br /> del(this, new TEventArgs<T>() { Value = t });<br /> }<br /> }<br /><br /> static void Main()<br /> {<br /> Test t = new Test();<br /> t.MyEvent1 += new EventHandler<TEventArgs<int>>((sender, args) => Console.WriteLine(args.Value + 1));<br /> t.MyEvent2 += new EventHandler<TEventArgs<string>>((sender, args) => Console.WriteLine(args.Value.Trim()));<br /><br /> t.OnNotify(23); // Prints 24<br /> t.OnNotify("Senthil Rocks "); // Prints Senthil Rocks<br /><br />
和remove访问器非常相似,但是编译器不喜欢事件声明是否具有通用参数.
The code inside the add and remove accessors is very similar, but the compiler doesn''t like if the event declaration has a generic parameter.
这篇关于泛型事件,或基于泛型类型的引发事件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!