C#里using的妙用(释放资源)
来源:互联网 发布:怎么添加网络打印机xp 编辑:程序博客网 时间:2024/06/08 16:56
其实关于using的作用,我想大家最多的用在引入命名空间。其实我在这之前也跟大家一样,不过今天在看一个小例子后,则让我产生了疑问。好拉,我先把代码附上吧。
using System;using System.IO;class Test { public static void Main() { try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("TestFile.txt")) { string line; // Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } }}
不知道上面的程序有没有一处让你比较困惑的呢,好拉,我就不卖关子了,我不懂的那一处如下:
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
.....................
}
一开始我以为是引入命名空间什么的,不过带着怀疑的态度,我到Q群里提出我自己的疑问。好在在他们的帮助下,让我纠正了我之前的错误想法。其实我们在连接数据库的时候也经常会使用到using的语法,类似下面这句:
using (SqlConnection conn = new SqlConnection(source))
{
//code
}
千万不要以为任何地方的实例化都可以这样使用在using块里的哦,一般是在需要自动释放资源的地方才会用到。其实说需要自动释放资源,可能大家也不是很理解。这样说吧,你想要能这样使用using块的话,你需要保证满足下面一点:
(1)此类实现了接口IDisposable(这个接口只有一个方法void Dispose()),当这个类在using中实例化的时候,using代码块结束时会自动调用这个类中实现了接口IDisposable的Dispose()方法。Dispose()方法中常用来做些释放资源的动作。
看看下面的一个简单的例子:
using System;class Program{ public static void Main(string[] args) { using (Test test = new Test()) { Console.WriteLine("Disposable is open!"); } Console.WriteLine("Disposable is none!"); Console.ReadKey(); }}public class Test:IDisposable{ #region IDisposable 成员 public void Dispose() { Console.WriteLine("Disposable is close!"); } #endregion}
这里输出的结果是:
Disposable is open!
Disposable is close!
Disposable is none!
好拉,今天的执笔就到此为止,谢谢大家!
注:ADO.net 中的连接等操作都实现了IDisposable接口,可以使用using进行资源管理!
using (SqlConnection conn = new SqlConnection(@"Data Source=(localDB)\V11.0; AttachDbFilename=E:\HUST-CODE\ADO_NETPra\ADO_NETPra\Database1.mdf;Integrated Security=True")) { conn.Open(); using (SqlCommand cmd=conn.CreateCommand()) { cmd.CommandText ="insert into Book(Name) values('charles')"; cmd.ExecuteNonQuery(); Console.WriteLine("执行成功!"); } }
- C#里using的妙用(释放资源)
- C#里using的作用------释放资源
- C# 中using 用来释放资源的用法
- c#事务、using释放资源、实体类的高级应用
- C# using 语句的妙用
- 资源的释放using与Dispose()
- C#的资源释放问题
- C# image资源的释放
- C#语言中的Using语句块确保资源被释放
- C#中using关键字在资源释放中的使用
- C# ASP.NET里@的妙用
- C# ASP.NET里@的妙用
- 提高C#编程水平的50个要点 之十五“使用 using 和 try-finally 来处理资源的释放”
- 使用using关键字同时释放多个资源的问题
- .NET 语言的 using statement 与资源释放
- 使用using关键字同时释放多个资源的问题
- c#是如何释放资源的
- C#释放未托管的资源
- scrapy学习笔记——Python网络爬虫利器(入门教程)
- SqlHelper
- 信号(Signal)与槽(Slot)-对象之间的一种高效通信接口
- 【HEVC学习与研究】36、对帧内预测参考数据进行滤波处理
- 【FZU 1978】Repair the brackets (Splay)
- C#里using的妙用(释放资源)
- Bridge模式(桥接模式 )
- 提高程序员工作效率的5个诀窍
- 主席树+LCA+spoj10628
- Linq to SQL查询数据库
- 迎接iOS8 - CoreLocation的变化
- 我的3d打印机制作心得
- android异步任务详解 AsynTask
- 【Unity Shaders】使用Unity Render Textures实现画面特效——画面特效中的叠加(Overlay)混合模式