gpt4 book ai didi

c# - DynamicMethod 调用因 StackOverFlowException 而终止

转载 作者:行者123 更新时间:2023-11-30 15:54:46 25 4
gpt4 key购买 nike

我有这个类(简化示例)

public class Foo
{
public object Bar(Type type)
{
return new object();
}
}

并且我想使用 DynamicMethodBar 实例上调用 Bar 方法,如图所示下面:

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));

但是,它并没有按预期工作,而是中止了

Process is terminated due to a StackOverFlowException.


有人可以告诉我我做错了什么吗?是不是参数不匹配?如何在 Bar 的特定实例上调用 Func

最佳答案

ilGenerator.EmitCall(OpCodes.Call, method, null); // I feel like this is wrong...

您目前正在编写方法;您可能打算在这里调用 methodInfo。请注意,这需要是一个 static 方法才能使用 Call - 如果它是一个实例方法,您可能应该使用 CallVirt。由于您没有传入 Foo 的实例,因此不清楚目标实例将来自何处;您需要将两个 值加载到堆栈上以调用实例方法Foo.Bar(Type type) - 而您目前只加载一个。

显示 Delegate.CreateDelegate 用法:

var methodInfo = typeof(Foo).GetMethod(nameof(Foo.Bar), new[] { typeof(Type) });
var foo = new Foo();

// if Foo is known ahead of time:
var f1 = (Func<Type, object>)Delegate.CreateDelegate(
typeof(Func<Type, object>), foo, methodInfo);

// if Foo is only known per-call:
var f2 = (Func<Foo, Type, object>)Delegate.CreateDelegate(
typeof(Func<Foo, Type, object>), null, methodInfo);

Console.WriteLine(f1(typeof(string)));

Console.WriteLine(f2(foo, typeof(string)));

关于c# - DynamicMethod 调用因 StackOverFlowException 而终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com