用户kokos通过使用关键字回答了c#的隐藏特性问题。你能详细说明一下吗?使用的用途是什么?


当前回答

当您希望在使用某个资源后将其销毁时,将使用Using。

例如,如果您分配了一个File资源,并且只需要在一段代码中使用它进行少量的读写,使用有助于在完成后立即处理File资源。

所使用的资源需要实现IDisposable才能正常工作。

例子:

using (File file = new File (parameters))
{
    // Code to do stuff with the file
}

其他回答

当你使用using时,它将调用using作用域末端对象上的Dispose()方法。因此,在Dispose()方法中可以有相当多出色的清理代码。

要点:

如果您实现了IDisposable,请确保在Dispose()实现中调用GC.SuppressFinalize(),否则自动垃圾收集将尝试出现并在某个时刻Finalize它,如果您已经Dispose()d了它,这至少会浪费资源。

比如:

using (var conn = new SqlConnection("connection string"))
{
   conn.Open();

    // Execute SQL statement here on the connection you created
}

这个SqlConnection将被关闭,而不需要显式地调用. close()函数,并且即使抛出异常也会发生,而不需要try/catch/finally。

因为很多人仍然这样做:

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

我想很多人仍然不知道你可以做到:

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

using可以用来调用IDisposable。它还可以用于别名类型。

using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;

using子句用于定义特定变量的作用域。

例如:

Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
    Conn.Open()

    // Execute SQL statements here.
    // You do not have to close the connection explicitly
    // here as "USING" will close the connection once the
    // object Conn goes out of the defined scope.
}