fork(1) 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. return Delegate.Combine(
  13. self.GetInvocationList()
  14. .Select(i => Delegate.CreateDelegate(type, i.Target, i.Method))
  15. .ToArray());
  16. }
  17.  
  18. public static T ConvertTo<T>(this Delegate self)
  19. {
  20. return (T)(object)self.ConvertTo(typeof(T));
  21. }
  22. }
  23.  
  24. public class MyEventArgs : EventArgs { }
  25.  
  26. public delegate void MyEventHandler(object sender, MyEventArgs e);
  27.  
  28. public class Foo {
  29.  
  30. public event EventHandler<MyEventArgs> MyEvent;
  31.  
  32. public bool IsEventNull() {
  33. return MyEvent == null;
  34. }
  35.  
  36. }
  37.  
  38. public class Bar {
  39. public Foo Impl = new Foo();
  40.  
  41. public event MyEventHandler MyEvent {
  42. add {
  43. Impl.MyEvent += value.ConvertTo<EventHandler<MyEventArgs>>();
  44. }
  45. Impl.MyEvent -= value.ConvertTo<EventHandler<MyEventArgs>>();
  46. }
  47. }
  48. }
  49.  
  50. public class Baz {
  51. public void MyHandler(object sender, MyEventArgs e) {}
  52. }
  53.  
  54. class Program
  55. {
  56. static void Main()
  57. {
  58. var bar = new Bar();
  59. var baz = new Baz();
  60.  
  61. Console.WriteLine("event is null: {0}", bar.Impl.IsEventNull());
  62.  
  63. bar.MyEvent += baz.MyHandler;
  64.  
  65. Console.WriteLine("event is null: {0}", bar.Impl.IsEventNull());
  66.  
  67. bar.MyEvent -= baz.MyHandler;
  68.  
  69. Console.WriteLine("event is null: {0}", bar.Impl.IsEventNull());
  70. }
  71. }
Success #stdin #stdout 0.03s 33696KB
stdin
Standard input is empty
stdout
event is null: True
event is null: False
event is null: True