内容显示页
 
类别:.Net + C# | 浏览(1537) | 2009-3-1 19:35:10

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.强制资源清理

引用本页地址:http://www.yongfa365.com/item/using.html
 
 
相关链接
 
网友评论:
姓名: 记住我
网址:
邮箱:
内容:
验证码:  验证码图片 看不清? 换张图试试
 
     
 
 
文章分类
 
 
.Net + C#(73)
 
 
ASP+VBS(161)
 
 
 
Linux(10)
 
 
 
web 2.0(26)
 
 
 
 
 
心程(68)
 
生活(97)
 
 
     

Power by :柳永法(yongfa365)'Blog  | 京ICP备07011491号  QQ:64049027  E-mail:64049027@qq.com yongfa365'CodePlex yongfa365'CodeGoogle

申请友情链接 要求:跟本站主题相类似正规网站,双方交换为首页位置

转载请注明来源,以便后人及时得到最新、修正、加强版!!!