I'm learning CIL by making my own functions at runtime with Reflection.Emit
. I'm actually surprised how easy things have been up until now but I've hit something that I can't guess my way through and I can't find anything relative in the docs.
I'm trying to create a function that simply prints a very simple class I have defined. If I change my code to print string
s, say, it works but it always fails to run when I pass an instance of my class A
.
What's weird is I can comment out my function body and it still fails with a TargetInvocationException
. It must be quite simple but I can't see what's up!
class A
{
public override string ToString()
{
return "AAA!";
}
}
class Program
{
static void Main(string[] args)
{
DynamicMethod func = new DynamicMethod("func", null, new Type[] { typeof(A) });
ILGenerator il = func.GetILGenerator();
//il.Emit(OpCodes.Ldarg_0);
//il.Emit(OpCodes.Box, typeof(A));
//il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(A) }));
il.Emit(OpCodes.Ret);
func.Invoke(null, new object[] { new A() });
Console.Read();
}
}
What am I doing so wrong to make this raise an exception? Why does this only happen with my classes?