using的使用方式

来源:互联网 发布:mac怎么显示桌面图标 编辑:程序博客网 时间:2024/06/06 05:12

1、命名空间

using System.Windows;

2、命名空间的别名

using System.Windows;using Froms = System.Windows.Forms;

例如引用:MessageBox.Show("Hello"); 因为在System.Windows和System.Windows.Forms命名空间中都有此类,可通过声明命名空间的别名来区分使用。

Form.MessageBox.Show("Hello");来简化替代System.Windows.Forms.MessageBox.Show("Hello");

3、using语句

提供能确保正确使用 IDisposable 对象的方便语法。

使用using可以确保并自动调用Dispose方法

                using(SqlConnection sqlConn = new SqlConnection(strConn))                {                    sqlConn.Open();                    //Do something                    Console.WriteLine("连接成功");                    sqlConn.Close();                }
等同于

            SqlConnection sqlConn = new SqlConnection(strConn);            try            {                sqlConn.Open();                //Do something                Console.WriteLine("连接成功");                sqlConn.Close();            }            finally            {                sqlConn.Dispose();            }

一般结合using和try..catch使用,既保证了调用Dispose方法,也做了异常处理。

            try            {                using(SqlConnection sqlConn = new SqlConnection(strConn))                {                    sqlConn.Open();                    //Do something                    Console.WriteLine("连接成功");                    sqlConn.Close();                }            }            catch(SqlException ex)            {                Console.WriteLine(ex.Message);            }




0 0
原创粉丝点击