通用类型的无用拳击

问题描述

此示例代码的TestMethod

public class Test<T> where T : class
{
    public void TestMethod(T param)
    {
        PrivateMethod(param);
    }

    private void PrivateMethod(object obj)
    {

    }
}

编译为以下IL代码:

IL_0000:  ldarg.0
IL_0001:  ldarg.1
IL_0002:  box        !T
IL_0007:  call       instance void class SensorPositioner2.Test`1<!T>::PrivateMethod(object)
IL_000c:  ret

我看到了box指令,在TestMethod调用期间会创建一个新对象吗?

如果是这样,如何避免这种情况?如果没有,为什么这里需要box

解决方法

由于object中的PrivateMethod()参数,因此需要装箱。您可以将PrivateMethod的签名更改为使用Generic Type而不是object以避免装箱。

private void PrivateMethod(T obj)
{

}

这将翻译为

 
IL_0001:  ldarg.0     
IL_0002:  ldarg.1     
IL_0003:  call        UserQuery+Test<>.PrivateMethod  // Your method
IL_0008:  nop         
IL_0009:  ret 

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...