I have this class (simplified example)
public class Foo
{
public object Bar(Type type)
{
return new object();
}
}
and I want to call the Bar
method on an instance of Bar
using DynamicMethod
as it is shown below:
MethodInfo methodInfo = typeof(Foo).GetMethod(nameof(Foo.Bar), new[] { typeof(Type) });
DynamicMethod method = new DynamicMethod("Dynamic Bar",
typeof(object),
new []{ typeof(Type) },
typeof(Foo).Module);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.EmitCall(OpCodes.Call, method, null); // I feel like this is wrong...
ilGenerator.Emit(OpCodes.Ret);
Func<Type, object> func = (Func<Type, object>) method.CreateDelegate(typeof(Func<Type, object>));
// Attempt to call the function:
func(typeof(Foo));
However, it does not work as wanted but rather aborts with
Process is terminated due to a StackOverFlowException.
Can someone please tell me what I am doing wrong? Is it a mismatch of the parameters?
How can I call the Func
on a specific instance of Bar
?