fork download
  1. using System;
  2. using System.Linq;
  3. using System.Threading;
  4.  
  5. static class Extensions
  6. {
  7. public static Delegate ConvertTo(this Delegate self, Type type)
  8. {
  9. if (type == null) { throw new ArgumentNullException("type"); }
  10. if (self == null) { return null; }
  11.  
  12. if (self.GetType() == type)
  13. return self;
  14.  
  15. return Delegate.Combine(
  16. self.GetInvocationList()
  17. .Select(i => Delegate.CreateDelegate(type, i.Target, i.Method))
  18. .ToArray());
  19. }
  20.  
  21. public static T ConvertTo<T>(this Delegate self)
  22. {
  23. return (T)(object)self.ConvertTo(typeof(T));
  24. }
  25. }
  26.  
  27. public class A { }
  28.  
  29. public class B : A {}
  30.  
  31. public delegate void MyEventHandler<in T>(object sender, T arg);
  32.  
  33. public class TheClass {
  34.  
  35. public event MyEventHandler<B> MyEvent {
  36. add {
  37. this._myEvent += value.ConvertTo<MyEventHandler<B>>();
  38. }
  39. this._myEvent -= value.ConvertTo<MyEventHandler<B>>();
  40. }
  41. }
  42.  
  43. private MyEventHandler<B> _myEvent;
  44.  
  45. public void RaiseEvent(B arg)
  46. {
  47. var handler = this._myEvent;
  48. if(handler != null)
  49. handler(this, arg);
  50. }
  51.  
  52. }
  53.  
  54. class Program
  55. {
  56. static void Main()
  57. {
  58. var obj = new TheClass();
  59.  
  60. obj.MyEvent += new MyEventHandler<B>((sender, e) => Console.WriteLine("B handler: Hey there from {0} with {1}!", sender, e));
  61. obj.MyEvent += new MyEventHandler<A>((sender, e) => Console.WriteLine("A handler: Hey there from {0} with {1}!", sender, e));
  62. obj.MyEvent += new MyEventHandler<object>((sender, e) => Console.WriteLine("Object handler: Hey there from {0} with {1}!", sender, e));
  63.  
  64. obj.RaiseEvent(new B());
  65. }
  66. }
Success #stdin #stdout 0.05s 24344KB
stdin
Standard input is empty
stdout
B handler: Hey there from TheClass with B!
A handler: Hey there from TheClass with B!
Object handler: Hey there from TheClass with B!