code_junkie

What's the MSIL to call a base class's event handler?

Nov 12th, 2011
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. public event EventHandler EventConsumed;
  2.  
  3. public virtual void OnEventConsumed(object sender, EventArgs e)
  4. {
  5. if (EventConsumed != null)
  6. EventConsumed(this, e);
  7. }
  8.  
  9. public override void OnEventConsumed(object sender, EventArgs e)
  10. {
  11. base.OnEventConsumed(sender, e);
  12. }
  13.  
  14. ...
  15.  
  16. MethodInfo baseMethod = typeof(EventConsumer).GetMethod("OnEventConsumed");
  17. MethodBuilder methodBuilder = typeBuilder.DefineMethod("OnEventConsumed",
  18. baseMethod.Attributes,
  19. baseMethod.CallingConvention,
  20. typeof(void),
  21. new Type[] {typeof(object),
  22. typeof(EventArgs)});
  23.  
  24. ILGenerator ilGenerator = methodBuilder.GetILGenerator();
  25.  
  26. // load the first two args onto the stack
  27. ilGenerator.Emit(OpCodes.Ldarg_1);
  28. ilGenerator.Emit(OpCodes.Ldarg_2);
  29.  
  30. // call the base method
  31. ilGenerator.EmitCall(OpCodes.Callvirt, baseMethod, new Type[0] );
  32.  
  33. // return
  34. ilGenerator.Emit(OpCodes.Ret);
  35.  
  36. ...
  37.  
  38. Common Language Runtime detected an invalid program.
  39.  
  40. .method public hidebysig virtual instance void OnEventConsumed(object sender, class [mscorlib]System.EventArgs e) cil managed
  41. {
  42. .maxstack 8
  43. L_0000: nop
  44. L_0001: ldarg.0
  45. L_0002: ldarg.1
  46. L_0003: ldarg.2
  47. L_0004: call instance void SubclassSpike.BaseClass::OnEventConsumed(object, class [mscorlib]System.EventArgs)
  48. L_0009: nop
  49. L_000a: ret
  50. }
  51.  
  52. // load 'this' and the first two args onto the stack
  53. ilGenerator.Emit(OpCodes.Ldarg_0);
  54. ilGenerator.Emit(OpCodes.Ldarg_1);
  55. ilGenerator.Emit(OpCodes.Ldarg_2);
  56.  
  57. // call the base method
  58. ilGenerator.EmitCall(OpCodes.Call, baseMethod, new Type[0] );
  59.  
  60. // return
  61. ilGenerator.Emit(OpCodes.Ret);
  62.  
  63. public virtual void OnEventConsumed(object sender, EventArgs e)
  64. {
  65. if (EventConsumed != null)
  66. EventConsumed(this, e);
  67. }
  68.  
  69. public virtual void OnEventConsumed(EventArgs e)
  70. {
  71. EventHandler handler = this.EventConsumed;
  72. if ( null != handler ) handler( this, e );
  73. }
Add Comment
Please, Sign In to add comment