我很不确定在块goto
内使用。using
例如:
using(stream s = new stream("blah blah blah"));
{
//do some stuff here
if(someCondition) goto myLabel;
}
现在如果someCondition
为真,代码执行将继续执行myLabel
,但是,对象会被释放吗?
我在这里看到了一些关于这个主题的很好的问题,但他们都在谈论不同的事情。
是的。
但为什么不自己尝试呢?
void Main()
{
using(new Test())
{
goto myLabel;
}
myLabel:
"End".Dump();
}
class Test:IDisposable
{
public void Dispose()
{
"Disposed".Dump();
}
}
结果:
处置
端
The using statement is essentially a try-finally block and a dispose pattern wrapped up in one simple statement.
using (Font font1 = new Font("Arial", 10.0f))
{
//your code
}
Is equivalent to
Font font1 = new Font("Arial", 10.0f);
try
{
//your code
}
finally
{
//Font gets disposed here
}
Thus, any jump from the "try-block", be it throwing an exception, the use of goto (unclean!) &tc. will execute the Disposal of the object being used in that "finally" block..
let's try:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int i = 0;
using (var obj = new TestObj())
{
if (i == 0) goto Label;
}
Console.WriteLine("some code here");
Label:
Console.WriteLine("after label");
Console.Read();
}
}
class TestObj : IDisposable
{
public void Dispose()
{
Console.WriteLine("disposed");
}
}
}
Console output is : disposed after label
Dispose() execute before codes after the label .
using(Stream s = new Stream("blah blah blah"))
{
if(someCondition) goto myLabel;
}
等于
Stream s;
try
{
s = new Stream("blah blah blah");
if(someCondition) goto myLabel;
}
finally
{
if (s != null)
((IDisposable)s).Dispose();
}
因此,只要您离开using块,该finally
块就会发生,无论是什么让它退出。