gpt4 book ai didi

c# - 使用在 Generic 类中创建的 Func 调用时 RuntimeHelpers.PrepareMethod 不起作用

转载 作者:行者123 更新时间:2023-12-01 21:55:25 25 4
gpt4 key购买 nike

我目前正在开发 Moq 框架的扩展,以模拟非虚拟方法的实现。我目前已经通过获取原始方法的方法句柄并将其与用户定义的 Func 的指针交换来完成此工作。

我仍然遇到的一个问题是,当我在 Moq 内部代码(在使用泛型的类中)创建 Func 时,我遇到了 RuntimeHelpers.PrepareMethod 的问题。 (在执行指针交换之前需要准备好 Func)。

当我在普通类(例如程序)中创建完全相同的 Func 时,一切正常。

进一步调查该问题可以追溯到调用类是否具有通用参数。

抛出异常:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: The given generic instantiation was invalid.

我已在以下代码块中隔离了问题:

class Program
{
static void Main(string[] args)
{
new WithoutGeneric().GoExecute();
new WithGeneric<string>().GoExecute();
}
}

public class WithoutGeneric
{
public void GoExecute()
{
//Works fine
StaticMethods.PrepareThisFunc(() => "Test");
}
}

public class WithGeneric<T>
{
public void GoExecute()
{
//Breaks
StaticMethods.PrepareThisFunc(() => "Test");
}
}

public static class StaticMethods
{
public static void PrepareThisFunc(Func<string> theFunc)
{
RuntimeHelpers.PrepareMethod(theFunc.Method.MethodHandle);
}
}

我也查看了当前的开源 CoreCLR 代码,但未能找出问题所在。

CoreCLR: https://github.com/dotnet/coreclr/blob/master/src/vm/reflectioninvocation.cpp

该行抛出异常:2435、2444、2447

有人知道如何解决此异常吗?

最佳答案

CLR 不知道 WithGeneric 类中的类型参数,它需要知道该类型参数才能创建调用图。

这样做可以解决问题:

class Program
{
static void Main(string[] args)
{
new WithoutGeneric().GoExecute();
new WithGeneric<string>().GoExecute();
}
}

public class WithoutGeneric
{
public void GoExecute()
{
//Works fine
StaticMethods.PrepareThisFunc1(() => "Test");
}
}

public class WithGeneric<T>
{
public void GoExecute()
{
//Works fine
StaticMethods.PrepareThisFunc2(() => "Test");
}
}

public static class StaticMethods
{
public static void PrepareThisFunc1(Func<string> theFunc)
{
RuntimeHelpers.PrepareMethod(theFunc.Method.MethodHandle);
}

public static void PrepareThisFunc2(Func<string> theFunc)
{
RuntimeHelpers.PrepareMethod(theFunc.Method.MethodHandle, new[] { typeof(string).TypeHandle });
}
}

关于c# - 使用在 Generic 类中创建的 Func<string> 调用时 RuntimeHelpers.PrepareMethod 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31754418/

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