Problem overriding abstract method with Reflection Emit

J

Jesse McGrew

I'm trying to use Reflection Emit to make a dynamic type, based on an
abstract class, that will implement the abstract methods from that
class. But when I call CreateType(), I get this error:

System.TypeLoadException: Method DoExplicitAction on type MyParser from
assembly SLAB, Version=0.0.0.0 is overriding a method impl.
at System.Reflection.Emit.TypeBuilder.TermCreateClass(TypeToken
handle, Module module)
at System.Reflection.Emit.TypeBuilder.CreateType()

I can resolve the error by marking the new method with
MethodAttributes.NewSlot, or by giving it a different name... but it
seems to me that's exactly the opposite of how virtual methods are
supposed to work! It should reuse a slot because it's overriding an
inherited method, right?

So my questions are...

1. Can I make this work without having to change the method name or give
it a new slot?

2. If I do change the method name or give it a new slot, will that cause
any problems at runtime? Will I still be able to call the new method
through a reference to the base type?

Here's my C# code to override the method:

//////////////////////////////////////
// define DoExplicitAction
MethodBuilder expl = ptb.DefineMethod(
"DoExplicitAction",
MethodAttributes.Family | MethodAttributes.Virtual |
MethodAttributes.HideBySig,
typeof(bool),
new Type[] { typeof(LadsDriver.Game), typeof(int), typeof(int) });
MethodInfo baseExpl = typeof(LadsDriver.Parser).GetMethod(
"DoExplicitAction",
BindingFlags.Instance | BindingFlags.NonPublic);
ptb.DefineMethodOverride(expl, baseExpl);
// (IL generation omitted)
//////////////////////////////////////

And here's the relevant part of the base class:

//////////////////////////////////////
public abstract class Parser
{
// (other fields and methods omitted)
protected abstract bool DoExplicitAction(Game game, int verb, int noun);
}
//////////////////////////////////////

Thanks,
Jesse
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top