一段时间以前,我编译了两个版本的代码,一个使用
事实证明,这种情况不再存在,当
(Nullable<T>)x.GetValueOrDefault(y)
,另一个使用(Nullable<T>)x ?? y)
。在反编译成IL后,我注意到空合并运算符被转换为GetValueOrDefault
调用。由于它是一个方法调用,可以传递表达式,在执行方法之前对其进行评估,因此y
似乎总是会被执行。例如:using System;
public static class TestClass
{
private class SomeDisposable : IDisposable
{
public SomeDisposable()
{
// Allocate some native resources
}
private void finalize()
{
// Free those resources
}
~SomeDisposable()
{
finalize();
}
public void Dispose()
{
finalize();
GC.SuppressFinalize(this);
}
}
private struct TestStruct
{
public readonly SomeDisposable _someDisposable;
private readonly int _weirdNumber;
public TestStruct(int weirdNumber)
{
_weirdNumber = weirdNumber;
_someDisposable = new SomeDisposable();
}
}
public static void Main()
{
TestStruct? local = new TestStruct(0);
TestStruct local2 = local ?? new TestStruct(1);
local2._someDisposable.Dispose();
}
}
似乎会导致一个不适应的对象,可能还会影响性能。
首先,这是真的吗?或者JIT或类似的东西是否会改变实际执行的ASM代码?
其次,有人能解释一下为什么会出现这种行为吗?
注意:这只是一个例子,不是基于真实代码的,请不要发表“这是糟糕的代码”之类的评论。
IL DASM:
好的,当我用.Net Framework 2.0编译它时,调用null合并和GetValueOrDefault生成了相同的代码。在.Net Framework 4.0中,它生成了这两个代码:
GetValueOrDefault:
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 19 (0x13)
.maxstack 2
.locals init ([0] valuetype [mscorlib]System.Nullable`1<int32> nullableInt,
[1] int32 nonNullableInt)
IL_0000: nop
IL_0001: ldloca.s nullableInt
IL_0003: initobj valuetype [mscorlib]System.Nullable`1<int32>
IL_0009: ldloca.s nullableInt
IL_000b: ldc.i4.1
IL_000c: call instance !0 valuetype [mscorlib]System.Nullable`1<int32>::GetValueOrDefault(!0)
IL_0011: stloc.1
IL_0012: ret
} // end of method Program::Main
空值合并运算符:
.method private hidebysig static void Main() cil managed
{
.entrypoint
// Code size 32 (0x20)
.maxstack 2
.locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0,
int32 V_1,
valuetype [mscorlib]System.Nullable`1<int32> V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj valuetype [mscorlib]System.Nullable`1<int32>
IL_0009: ldloc.0
IL_000a: stloc.2
IL_000b: ldloca.s V_2
IL_000d: call instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
IL_0012: brtrue.s IL_0017
IL_0014: ldc.i4.1
IL_0015: br.s IL_001e
IL_0017: ldloca.s V_2
IL_0019: call instance !0 valuetype [mscorlib]System.Nullable`1<int32>::GetValueOrDefault()
IL_001e: stloc.1
IL_001f: ret
} // end of method Program::Main
事实证明,这种情况不再存在,当
HasValue
返回false时,它会直接跳过GetValueOrDefault
的调用。
y
是调用一个返回需要被处理的对象的方法,则无论如何,如果x
为空,则会存在泄漏问题。 - M.Babcocklocal
不为null并且该方法确实被调用,那么就会出现泄漏,因为结果将从垃圾回收器(GC)中被收集而不被处理。要回答这个问题,即确认该方法是否每次都被调用,你可以在方法中设置断点并运行它。 - M.Babcock