C# 转到使用块的内部,对象是否会被处置?

C# 转到使用块的内部,对象是否会被处置?,c#,.net,.net-4.0,C#,.net,.net 4.0,我不确定是否在使用块中使用转到 例如: using(stream s = new stream("blah blah blah")); { //do some stuff here if(someCondition) goto myLabel; } 现在,如果someCondition为真,代码执行将转到myLabel,但是,对象是否会被释放 我在这里看到了一些关于这个话题的非常好的问题,但它们都谈论不同的事情。是的 但是为什么不自己试试呢 void Main() {

我不确定是否在
使用
块中使用
转到

例如:

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();
    }
}
结果:

处置
结束


using语句本质上是一个try-finally块和一个dispose模式,封装在一个简单语句中

using (Font font1 = new Font("Arial", 10.0f))
{
    //your code
}
相当于

Font font1 = new Font("Arial", 10.0f);
try
{
     //your code
}
finally
{
     //Font gets disposed here
}
因此,任何从“try块”的跳转,无论是抛出异常,还是使用goto(unclean!)&tc。将对“最终”块中使用的对象执行处置。

让我们试试:

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");
        }
    }

}
控制台输出为: 乐意 后标签

Dispose()在标签后面的代码之前执行

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块中使用goto。
-我不确定是否在一般情况下使用
goto
,而不仅仅是在
块中使用
。令我惊讶的是,C#的创建者竟然有能力构建一种高级复杂的编程语言,然后使用goto。你知道,你不是在汇编中编程。
goto有它的优点。:)-@SeanVaughn,真的吗?我写C#代码已经9年了,但仍然没有看到任何优势。因为每个答案都有相同的观点,所以选择一个是不相关的。但是,由于您的代表级别较低: