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

C# C“中的匿名对象”;使用;声明可靠吗?,c#,dispose,idisposable,using,using-statement,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 { pub

想象一下这个片段:

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
在内部,我使用
使用(new Report.Indent())
而不是使用我找到的唯一文档版本,即
使用(Report.Indent r=new Report.Indent())

但是,在我的简短版本中,我是否可以确保每次都会对那些未命名的缩进对象调用
Dispose()

附笔。
是的,
使用
可以确保即使是“匿名对象”也会被处理掉


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

没关系。但我会避免使用静态变量,这是一种可识别的滥用。是的,很难放弃。但迟早你会遇到一个程序员,他发誓处理对象是可选的,当程序将在几毫秒后终止时,这毫无意义。他当然是对的。祝你好运,向他解释你更改了合同。@DanielA.White-也就是说,
Level
variable?当然,如果我制作了整个
报告
静态
,应该没问题,也不会引起怀疑,对吧?还是我应该避免使用可疑的代码?我会同时避免使用静态代码。@HansPassant-我喜欢读“滥用”这个词:)我只认为这个实现是一种委托的方式,确保我在运行时关闭了正确位置的所有括号,同时使代码更易于阅读(多亏了编辑器的括号索引)。以前我曾参与过
++Report.Indent
--Report.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