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


当前回答

当使用ADO时。NET中,你可以在connection对象或reader对象上使用keywork。这样,当代码块完成时,它将自动处理您的连接。

其他回答

使用using语句的原因是为了确保对象一旦超出作用域就会被释放,并且不需要显式代码来确保发生这种情况。

正如在理解c#中的“using”语句(codeproject)和使用实现IDisposable的对象(microsoft)中,c#编译器转换

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();
}

to

{ // Limits scope of myRes
    MyResource myRes= new MyResource();
    try
    {
        myRes.DoSomething();
    }
    finally
    {
        // Check for a null resource.
        if (myRes != null)
            // Call the object's Dispose method.
            ((IDisposable)myRes).Dispose();
    }
}

c# 8引入了一个新的语法,命名为“using declarations”:

using声明是一个前面有using关键字的变量声明。它告诉编译器,所声明的变量应该在封闭作用域的末尾被处理。

所以上面的等效代码是:

using var myRes = new MyResource();
myRes.DoSomething();

当控制离开包含范围(通常是一个方法,但也可以是一个代码块)时,myRes将被释放。

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

要点:

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

因为很多人仍然这样做:

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。

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

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

例子:

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

Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.

这允许您使用非常好的使用语法来指示所述操作的显式开始和结束。这也是系统如何。事务处理可以工作。