What are the uses of “using” in C#

2018-12-31 02:42发布

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of using?

29条回答
泪湿衣
2楼-- · 2018-12-31 02:51

using can be used to call IDisposable. It can also be used to alias types.

using (SqlConnection cnn = new SqlConnection()) { /*code*/}
using f1 = System.Windows.Forms.Form;
查看更多
若你有天会懂
3楼-- · 2018-12-31 02:51

Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no mater how you exit the using block, it will always dispose the object. This includes returns and exceptions.

using (var db = new DbContext())
{
    if(db.State == State.Closed) throw new Exception("Database connection is closed.");
    return db.Something.ToList();
}

It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.

查看更多
查无此人
4楼-- · 2018-12-31 02:51

Another great use of using is when instantiating a modal dialog.

Using frm as new Form1

Form1.ShowDialog

' do stuff here

End Using
查看更多
刘海飞了
5楼-- · 2018-12-31 02:55

Another example of a reasonable use in which the object is immediately disposed:

using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) 
{
    while (myReader.Read()) 
    {
        MyObject theObject = new MyObject();
        theObject.PublicProperty = myReader.GetString(0);
        myCollection.Add(theObject);
    }
}
查看更多
步步皆殇っ
6楼-- · 2018-12-31 02:58

Since a lot of people still do:

using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
   //code
}

I guess a lot of people still don't know that you can do:

using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
   //code
}
查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 02:58

The using statement tells .NET to release the object specified in the using block once it is no longer needed. So you should use 'using' block for classes that require cleaning up after them, like System.IO Types.

查看更多
登录 后发表回答