Dict.CN 在线词典, 英语学习, 在线翻译
随笔-173  评论-140  文章-1  trackbacks-1

C# 编程语言的 using 语句通过简化必须编写以便创建和清理对象的代码,使得对 Dispose 方法的调用更加自动化。using 语句获得一个或多个资源,执行您指定的语句,然后处置对象。请注意,using 语句只适用于这样的对象:这些对象的生存期不超过在其中构建这些对象的方法。下面的代码示例将创建并清理 ResourceWrapper 类的实例,如 C# 示例实现 Dispose 方法中所示。

 

class myApp
{
   
public static void Main()
   
{
      
using (ResourceWrapper r1 = new ResourceWrapper())
      
{
         
// Do something with the object.
         r1.DoSomething();
      }

   }

}

以上合并了 using 语句的代码与下面的代码等效。

 

 

class myApp
{
   
public static void Main()
   
{
      ResourceWrapper r1 
= new ResourceWrapper();
      
try
      
{
         
// Do something with the object.
         r1.DoSomething();
      }

      
finally
      
{
         
// Check for a null resource.
         if (r1 != null)
         
// Call the object's Dispose method.
         r1.Dispose();
      }

   }

}
posted on 2008-05-09 10:52 Robot·H 阅读(199) 评论(3)  编辑 收藏 所属分类: C#2.0

评论:
#1楼  2008-05-09 12:09 | 镜涛      
沙发
  回复  引用  查看    
#2楼 [楼主] 2008-05-10 17:44 | Robot·H      
@镜涛
有沙发,没有板凳啊。
  回复  引用  查看    
#3楼 [楼主] 2008-05-25 13:07 | Robot·H      
/*
using 用法
* using +namespace ,这样可以直接用namespace的所有类型,而不用指定命名空间的详细路径。
using System;
Console.WriteLine("using System; is to omit System. later");
* using +alias=namespace
using a=System;
* using is easy to dispose object
*/
using System;
using System.IO;
class Test
{

static void Main()
{
Console.WriteLine("Enter file path");
string fileSec = Console.ReadLine();
FileStream fs = new FileStream(fileSec, FileMode.OpenOrCreate);
using (A a = new A(fs))
{
a.DoSomething();
}

Console.ReadLine();


//A a = new A();
//try
//{
// DoSomething();
//}
//finally
//{
// if (a != null)
// {
// a.Dispose();
// }
//}
}
}
class A:IDisposable
{
private bool _dispose;
private Stream _stream;
public A(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("ArgumentNullException");
}
if (!stream.CanRead)
{
throw new ArgumentException("the stream is not readable");
}

_stream = stream;
}

public void DoSomething()
{
//...
System.Console.Write("the stream length:"+_stream.Length);
}

#region IDisposable 成员 //implement interface

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

#endregion

public void Dispose(bool dispose)
{
if (!_dispose)
{
if (dispose)
{
if (_stream != null)
{ _stream.Dispose(); }
}
_stream = null;
}
}
}
  回复  引用  查看    

标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
 
另存  打印
 


Msn:glory_yimart@hotmail.com QQ:2839849 Emal:yimart at 163.com