就是连接数据库的时候,C#创建连接对象为什么要用using????

解决方案 »

  1.   

    using System;namespace Text
    {
        public class Program
        {        static void Main(string[] args)
            {
                using (TestClass test = new TestClass())
                {
                }            Console.ReadKey();
            }
        }    public class TestClass  : IDisposable   
        {
            public void Dispose()
            {
                Console.WriteLine("自动执行Dispose");
            }
        }
    }
      

  2.   

    using System;namespace Text
    {
        public class Program
        {
            static void Main(string[] args)
            {
                TestClass test = new TestClass();
                try
                {
                }
                finally
                {
                    test.Dispose();
                }            Console.ReadKey();
            }
        }    public class TestClass  : IDisposable   
        {
            public void Dispose()
            {
                Console.WriteLine("人工执行Dispose");
            }
        }
    }
      

  3.   

    用using可以保证连接会被关闭。
      

  4.   

    主要是为了自动式放~using块结束的时候会自动释放你创建的资源~
      

  5.   

    using会自动调用new出来对象的Dispose方法,可以保证在各种情况下包括异常时都能释放非托管资源,数据库连接分配了非脱光资源,所以应该用using,c#会把using编译成try/finally结构,在finally里调用using中表达式的对象的Dispose方法,如果没有Dispose方法则什么都不做,