问题描述
任何人任何想法,为什么这限制了T可类泛型方法将有拳击的指令在生成MSIL code?
Anyone any idea why a generic method which constrains T to class would have boxing instructions in the generates MSIL code?
我被这非常惊讶,因为肯定,因为T被被限制为引用类型生成code应该不需要执行任何拳击。
I was quite surprised by this since surely since T is being constrained to a reference type the generated code should not need to perform any boxing.
下面是C#code:
protected void SetRefProperty<T>(ref T propertyBackingField, T newValue) where T : class
{
bool isDifferent = false;
// for reference types, we use a simple reference equality check to determine
// whether the values are 'equal'. We do not use an equality comparer as these are often
// unreliable indicators of equality, AND because value equivalence does NOT indicate
// that we should share a reference type since it may be a mutable.
if (propertyBackingField != newValue)
{
isDifferent = true;
}
}
下面是产生IL:
.method family hidebysig instance void SetRefProperty<class T>(!!T& propertyBackingField, !!T newValue) cil managed
{
.maxstack 2
.locals init (
[0] bool isDifferent,
[1] bool CS$4$0000)
L_0000: nop
L_0001: ldc.i4.0
L_0002: stloc.0
L_0003: ldarg.1
L_0004: ldobj !!T
L_0009: box !!T
L_000e: ldarg.2
L_000f: box !!T
L_0014: ceq
L_0016: stloc.1
L_0017: ldloc.1
L_0018: brtrue.s L_001e
L_001a: nop
L_001b: ldc.i4.1
L_001c: stloc.0
L_001d: nop
L_001e: ret
}
注意在中!!牛逼的说明。
任何人,为什么这是正在发生什么想法?
Anyone any idea why this is being generated?
任何人任何想法如何避免这种情况?
Anyone any ideas how to avoid this?
谢谢,菲尔
推荐答案
您不必担心任何性能劣化从中
指令,因为如果它的参数是引用类型,在中
指令不执行任何操作。虽然它仍然奇怪的是,中
指令,甚至被创建(也许lazyiness /很容易在code代的设计?)。
You don't have to worry about any performance-degradations from the box
instruction because if its argument is a reference type, the box
instruction does nothing. Though it's still strange that the box
instruction has even been created (maybe lazyiness/easier design at code generation?).
这篇关于为什么通用方法的T constaint:类结果在拳击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!