- using System; //using 引用命名空间
- using System.Collections.Generic;
- using System.Text;
- using System.IO;
- using System.Data;
- using System.Data.SqlClient;
- using System.Xml;
- using Excel = Microsoft.Office.Interop.Excel; //using 创建别名
- namespace statement
- {
- //指定Font类的别名为F
- using F = System.Drawing.Font;
- class Program
- {
- static void Main(string[] args)
- {
- //using 强制资源清理
- using (TextWriter writer = File.CreateText(@"E:\test.txt"))
- {
- //使用别名来实例化对象
- F font = new F("宋体", 12);
- writer.WriteLine(font.Name.ToString() + font.Size.ToString());
- }
- //上面的using语句等价于
- TextWriter w = File.CreateText(@"E:\test.txt");
- try
- {
- F font = new F("宋体", 12);
- w.WriteLine(font.Name.ToString() + font.Size.ToString());
- }
- finally
- {
- if (w != null) w.Dispose();
- }
- //也可以在using之前声明对象
- TextReader r = File.OpenText("E://test.txt");
- using (r)
- {
- Console.WriteLine(r.ReadToEnd());
- }
- //对象类型相同时,可以使用多个:
- using (StreamReader reader = new StreamReader("1.txt"), reader2 = new StreamReader("2.txt"))
- {
- //do something
- }
- //嵌套using
- using (SqlConnection conn = new SqlConnection())
- {
- using (SqlCommand cmd = new SqlCommand())
- {
- //嵌套using 缩进太多,从而不便于观察代码,可以用,但适可而止,如果有多层嵌套请使用 多重using
- //这一层如果出错,不会影响上一层conn的释放,也就是说可以这么用
- }
- }
- //多重using
- using (StreamReader reader = new StreamReader("1.txt"))
- using (StreamWriter writer = new StreamWriter("1.txt"))
- using (SqlConnection conn = new SqlConnection())
- using (SqlCommand cmd = new SqlCommand())
- {
- //这样操作也可以最后释放所有资源,并且不会因嵌套using而产生太多缩进
- //通过reflector观察发现系统最后会生成跟嵌套using相同的代码
- }
- }
- }
- }
- //总结起来如下:
- //1.引入命名空间
- //2.创建别名
- //3.强制资源清理
using的几种用法 C#
最新推荐文章于 2024-05-23 17:56:07 发布