C# "using"语句中的匿名对象可靠吗?

标签 c# dispose idisposable using using-statement

想象一下这个片段:

using System;



public class Report {
    static int Level=0;

    public static void WriteLine(string Message) {
        Console.WriteLine("{0}{1}",new String(' ',4*Level),Message);
    }

    public class Indent:IDisposable {
        public Indent()            { Report.WriteLine("{"); ++Level; }
        void IDisposable.Dispose() { --Level; Report.WriteLine("}"); }
    }
}



class Program {
    static void Main() {
        Report.WriteLine("Started");
        Report.WriteLine("Calling submethod");
        using(new Report.Indent()) {
            Report.WriteLine("Submethod started");
            using(new Report.Indent()) Report.WriteLine("Subsub, maybe?");
            Report.WriteLine("Submethod reporting everything is fine");
            Report.WriteLine("Submethod finished");
        }
        Report.WriteLine("Finished");
    }
}

产生结果:

Started
Calling submethod
{
    Submethod started
    {
        Subsub, maybe?
    }
    Submethod reporting everything is fine
    Submethod finished
}
Finished

在内部,我正在使用 using(new Report.Indent()) 而不是坚持使用我发现的唯一记录版本,即 using(Report.Indent r=new Report.Indent ()).

但是,在我的简短版本中,我能否确定 Dispose() 每次都会对那些未命名的 Indent 对象调用?

附言

// btw, I used word "anonymous" in the title, but I'm not sure that's what new objects that aren't assigned to any named variable should be called

最佳答案

是的,使用 确保即使是“匿名对象”也总是被丢弃。

在内部,using 存储在局部变量中进​​入 block 时使用的任何值。这个存储的值在退出 block 时被释放。

关于C# "using"语句中的匿名对象可靠吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26343292/

相关文章:

c# - 防止多次处理对象

.net - 我必须在 FolderBrowserDialog 上调用 Dispose 方法吗?

c# - 告诉 FxCop 另一个方法正在调用 dispose

c# - 当 Ninject 被用作依赖解析器时,如何在 asp.net mvc3 App 中处理 DbContext(或对象)

c# - 在按钮集合中创建、使用和比较元素

c# - DLL插件调试不起作用

unity-container - 在 Unity 中需要处理?

vb.net - 我是否需要释放 COM Interop 对象的内部对象?

c# - 将数据库 24 小时制转换为 12 小时制

C# SVG(使用 device-cmyk() 或 icc-color())到 PDF 转换