C# 通用对象函数指针,相同地址?

C# Generic Object Function Pointers, Same Address?

我正在尝试获取泛型 class 中方法的函数指针。我一直在使用 MethodInfo.MethodHandle.GetFunctionPointer() 来这样做,但由于我最近一直在使用通用 classes,上述方法一直在按照我认为的方式工作。

考虑以下几点:

public class Example<T>
{
    public bool doSomething()
    {
        /*some work*/
        return true;
    }
}

以下所有return相同的内存地址:

typeof(Example<int>).GetMethod("doSomething").MethodHandle.GetFunctionPointer()
typeof(Example<bool>).GetMethod("doSomething").MethodHandle.GetFunctionPointer()
typeof(Example<SomeClass>).GetMethod("doSomething").MethodHandle.GetFunctionPointer()

我不确定这是为什么。谁能给我解释一下?记忆中真的只有那个函数的一个版本吗?

这肯定会引起一些人的注意。我正在修改游戏代码而无需访问源代码。以这种方式注入代码是这一行的常见做法。游戏的最终用户许可协议也明确允许此类注入,只要不直接修改原始 dll 文件即可。

这是因为,正如 Anders Hejlsberg(首席 C# 架构师)在 article 中所述:

Now, what we then do is for all type instantiations that are value types—such as List<int>, List<long>, List<double>, List<float>—we create a unique copy of the executable native code. So List<int> gets its own code. List<long> gets its own code. List<float> gets its own code. For all reference types we share the code, because they are representationally identical. It's just pointers.

在您的示例中,boolint 是值类型。他们每个人都有自己的副本,因此他们有不同的指向 doSomething 的指针。 SomeClass 是引用类型(我假设)。因此它与其他引用类型共享其代码,但不与值类型共享。所以它也有不同的 doSomething 指针(不同于 boolint 版本)。如果您使用其他引用类型 (SomeOtherClass) - 它将具有与 doSomething.

SomeClass 版本相同的指针