大多数在网上找到的示例,当明确不使用 "using" 时,模式看起来像这样:
SqlConnection c = new SqlConnection(@"...");
try {
c.Open();
...
} finally {
if (c != null) //<== check for null
c.Dispose();
}
如果你使用 "using" 并查看生成的 IL 代码,你可以看到它会生成对 null 的检查。
L_0024: ldloc.1
L_0025: ldnull
L_0026: ceq
L_0028: stloc.s CS$4$0000
L_002a: ldloc.s CS$4$0000
L_002c: brtrue.s L_0035
L_002e: ldloc.1
L_002f: callvirt instance void [mscorlib]System.IDisposable::Dispose()
L_0034: nop
L_0035: endfinally
我理解IL代码被转译为检查空值的原因(不知道您在using块内部做了什么),但如果您正在使用try..finally并且您完全控制如何在try..finally块内使用IDisposable对象,那么您真的需要检查空值吗? 如果需要,为什么?