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


当前回答

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.
}

其他回答

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

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

“using”还可以用于解决名称空间冲突。

关于这个主题,我写了一个简短的教程,请参阅http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/。

另一个对象立即被处置的合理使用的例子:

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);
    }
}

并不是说它非常重要,而是使用它还可以用来动态地更改资源。

是的,正如前面提到的,是一次性的,但是可能您特别不希望在执行的其余时间内它们与其他资源不匹配。所以你要把它处理掉,这样它就不会影响到其他地方。

using关键字定义对象的作用域,然后在作用域完成时释放对象。为例。

using (Font font2 = new Font("Arial", 10.0f))
{
    // Use font2
}

请参阅这里关于c#使用关键字的MSDN文章。