想象一下这个片段:
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/