I have a class called EventConsumer which defines an event EventConsumed and a method OnEventConsumed as follows:
public event EventHandler EventConsumed;
public virtual void OnEventConsumed(object sender, EventArgs e)
{
if (EventConsumed != null)
EventConsumed(this, e);
}
I need to add attributes to the at OnEventConsumed runtime, so I'm generating a subclass using System.Reflection.Emit. What I want is the MSIL equivalent of this:
public override void OnEventConsumed(object sender, EventArgs e)
{
base.OnEventConsumed(sender, e);
}
What I have so far is this:
...
MethodInfo baseMethod = typeof(EventConsumer).GetMethod("OnEventConsumed");
MethodBuilder methodBuilder = typeBuilder.DefineMethod("OnEventConsumed",
baseMethod.Attributes,
baseMethod.CallingConvention,
typeof(void),
new Type[] {typeof(object),
typeof(EventArgs)});
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
// load the first two args onto the stack
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Ldarg_2);
// call the base method
ilGenerator.EmitCall(OpCodes.Callvirt, baseMethod, new Type[0] );
// return
ilGenerator.Emit(OpCodes.Ret);
...
I create the type, create an instance of the type, and call its OnEventConsumed function, and I get:
Common Language Runtime detected an invalid program.
...which is not exactly helpful. What am I doing wrong? What's the correct MSIL to call the base class's event handler?