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

标签 c# generics reflection function-pointers cil

我正在尝试获取泛型类中方法的函数指针。我一直在使用 MethodInfo.MethodHandle.GetFunctionPointer() 来执行此操作,但由于我最近一直在使用泛型类,所以上述方法一直按我预期的方式工作。

考虑以下几点:

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

以下都返回相同的内存地址:

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

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

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

最佳答案

那是因为,如本 article 中所述作者:Anders Hejlsberg(首席 C# 架构师):

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 ) - 它将具有与 SomeClass 相同的指针doSomething 的版本.

关于C# 通用对象函数指针,相同地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312324/

相关文章:

c# - 获取哈希集 C# 中的值索引

generics - 接口(interface)中的 TypeScript 通用方法签名

c - 在链接列表中使用 "void *"时出现问题

java - 比较 ASM MethodNode 参数

c# - Azure ML Web 服务超时

c# - 在最大化代码重用的同时使用 C# 接口(interface)

c# - 泛型方法以不同于泛型类型的方式处理 IEnumerable

java - 为当前线程禁用 Java 反射

Java:如何检查字段是否为 java.util.Collection 类型

c# - 反序列化有时是 int 值的 json 对象