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


当前回答

只是添加了一点我很惊讶没有出现的东西。using最有趣的特性(在我看来)是无论你如何退出using块,它总是会释放对象。这包括返回和异常。

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

这与是否抛出异常或是否返回列表无关。DbContext对象总是会被释放。

其他回答

因为很多人仍然这样做:

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
}

总之,当您使用实现IDisposable类型的局部变量时,总是毫无例外地使用using1。

如果使用非局部IDisposable变量,则始终实现IDisposable模式。

两条简单的规则,无一例外。否则,防止资源泄漏是一件非常痛苦的事情。


1):唯一的例外是-当你处理异常时。在finally块中显式调用Dispose的代码可能会更少。

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

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 LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;

正如你所看到的,这被称为使用别名指令,它可以用来隐藏冗长的引用,如果你想在你的代码中明显地引用什么 如。

LegacyEntities.Account

而不是

CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account

或者简单地

Account   // It is not obvious this is a legacy entity

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

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

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

例子:

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