Is something like this possible?
//
// create a delegate
Action<Type> action = (t) => t.DoSomething;
//
// get the IL generator for a method
ILGenerator il = myMethodBuilder.GetILGenerator();
//
// try and call the delegate
il.EmitCall(OpCodes.Callvirt, action.Method, null);
Im getting a MethodAccessException whenever I try to invoke the method.
Thanks
This is because the method generated for the C#
(t) => t.DoSomethinglambda is private. Chances are this lambda won’t be static, either, depending on which of the local variables it captures from the outer method. You’re issuing acallvirtinstruction but you don’t appear to be supplying an instance.You can verify this by loading your application’s code in Reflector and looking at the implementation of your
(t) => t.DoSomethinglambda.You need to either:
public staticmethod in an externally-visible classAction<Type>in your IL method, generate code that callsAction<Type>.Invoke, then pass youractionvariable into the generated method