孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

using关键字可以支持IDisposable模式,可以在后面的圆括号中获得自由,这些自由作为局部变量,它们的作用范围限制在大括号限定的范围内。

我们看一下例子

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace DisposeAndUsing
 7 {
 8     class Program
 9     {
10         public class A : IDisposable
11         {
12             private bool disposed = false;
13             private void Dispose(bool disposing)
14             {
15                 if (!disposed)
16                 {
17                     if (disposing)
18                     {
19 
20                     }
21                     Console.WriteLine("Cleaning up object");
22                     disposed = true;
23                 }
24             }
25 
26             public void Dispose()
27             {
28                 Dispose(true);
29                 GC.SuppressFinalize(this);
30             }
31 
32             public void DoSomething()
33             {
34                 Console.WriteLine("A.SoSomething()");
35             }
36 
37             ~A()
38             {
39                 Console.WriteLine("Finalizing");
40                 Dispose(false);
41             }
42         }
43 
44         static void Main(string[] args)
45         {
46             using (A a = new A())
47             {
48                 a.DoSomething();
49             }
50 
51             using (A a = new A(), b = new A())
52             {
53                 a.DoSomething();
54                 b.DoSomething();
55             }
56             Console.ReadLine();
57         }
58     }
59 }

using语句要求进程获得的所有资源能隐式的转换为IDisposable.这意味着它们必须实行IDisposable接口,否则会得到一个编译警告。

posted on 2012-12-09 13:00  孤独的猫  阅读(179)  评论(0编辑  收藏  举报