问题描述
在我的公司中,我看到的是这样的代码
In my company, I am seeing code like this
using (LoggerFactory.GetTracer(_log.ModuleName + "._GetAccessTokenFromWns"))
{...}
当我向上看时,我发现它处理了由使用"括号内声明的变量所引用的对象.
When I looked up, I learned it disposes the objects referred by variables declared inside "Using" parenthesis.
它对上面的代码(没有指向工厂返回的对象的变量)有帮助吗?
Does it also help for code like above, where there is no variable referring to the object returned by the factory?
谢谢
推荐答案
看到您的问题后,我编写了一个简单的代码,如下所示:
After I see your question I write a simple code like this:
using (new FileStream("sample.txt",FileMode.CreateNew))
{
}
然后查看生成的IL code
:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 35 (0x23)
.maxstack 2
.locals init ([0] class [mscorlib]System.IO.FileStream CS$3$0000,
[1] bool CS$4$0001)
IL_0000: nop
IL_0001: ldstr "asdas.txt"
IL_0006: ldc.i4.1
IL_0007: newobj instance void [mscorlib]System.IO.FileStream::.ctor(string,
valuetype [mscorlib]System.IO.FileMode)
IL_000c: stloc.0
.try
{
IL_000d: nop
IL_000e: nop
IL_000f: leave.s IL_0021
} // end .try
finally
{
IL_0011: ldloc.0
IL_0012: ldnull
IL_0013: ceq
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: brtrue.s IL_0020
IL_0019: ldloc.0
IL_001a: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_001f: nop
IL_0020: endfinally
} // end handler
IL_0021: nop
IL_0022: ret
} // end of method Program::Main
如您所见,它仍在调用Dispose
方法,它在try
块之前创建FileStream
实例,然后在finally
中调用Dispose
方法,我认为这是using
语句.
As you can see it is still calling the Dispose
method.It creates FileStream
instance before try
block, then calling the Dispose
method in the finally
.I think this is another advantage of using
statements.
这篇关于是“使用{}"即使没有变量引用对象,也要处置它的优良作法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!