代码一:context.Response.ContentType = "text/JPEG";
        string fullpath = context.Server.MapPath("a.jpg");
        string name = context.Request["Name"];        using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(fullpath))
        {
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
            {
                g.DrawString(name, new System.Drawing.Font("雅黑", 36), System.Drawing.Brushes.Red, 50, 70);
            }
            bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
代码二:context.Response.ContentType = "text/JPEG";
        string fullpath = context.Server.MapPath("a.jpg");
        string name= context.Request["Name"];
        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(fullpath);
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
        g.DrawString(name, new System.Drawing.Font("雅黑", 36), System.Drawing.Brushes.Red, 50, 70);        bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
二段代码中的实现的功能都一样,为什么第一段中要用using包起来。使用using 与不使用using的区别在哪里?

解决方案 »

  1.   

    C# 通过 .NET Framework 公共语言运行库 (CLR) 自动释放用于存储不再需要的对象的内存。内存的释放具有不确定性;一旦 CLR 决定执行垃圾回收,就会释放内存。但是,通常最好尽快释放诸如文件句柄和网络连接这样的有限资源。 using 语句允许程序员指定使用资源的对象应当何时释放资源。为 using 语句提供的对象必须实现 IDisposable 接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源。
      

  2.   

    using关键字的用法以及作用本来想自己讲的,发现搜一下后,别人比我讲得好。
      

  3.   

    Using (TestObject a = new TestObject()) { 
    // 使用对象 

    //对象资源被释放 
    大括号完毕释放