ens*_*tis 3 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");
}
}
Run Code Online (Sandbox Code Playgroud)
产生结果:
Started
Calling submethod
{
Submethod started
{
Subsub, maybe?
}
Submethod reporting everything is fine
Submethod finished
}
Finished
Run Code Online (Sandbox Code Playgroud)
在里面,我使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
918 次 |
| 最近记录: |