C#中的匿名对象”;使用“;声明可靠

本文关键字:使用 声明 对象 | 更新日期: 2023-09-27 18:26:24

想象一下这个片段:

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()吗?

P.S

// 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

C#中的匿名对象”;使用“;声明可靠

是的,using枚举即使是"匿名对象"也总是被处理掉。

在内部,using存储在局部变量中输入块时使用的任何值。此存储的值在退出块时被释放。