C#中“使用”的用途是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/75401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:12:33  来源:igfitidea点击:

What are the uses of "using" in C#?

提问by ubermonkey

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

用户kokos通过提及关键字回答了C#的精彩隐藏功能问题using。你能详细说明一下吗?有什么用途using

采纳答案by paulwhit

The reason for the usingstatement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

using声明的原因是为了确保对象一旦超出范围就被处理掉,并且不需要显式代码来确保发生这种情况。

As in Understanding the 'using' statement in C# (codeproject)and Using objects that implement IDisposable (microsoft), the C# compiler converts

正如在了解 C# (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 introduces a new syntax, named "using declarations":

C# 8 引入了一种新语法,名为“使用声明”:

A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

using 声明是前面带有 using 关键字的变量声明。它告诉编译器声明的变量应该在封闭范围的末尾处理。

So the equivalent code of above would be:

所以上面的等效代码是:

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

And when control leaves the containing scope (usually a method, but it can also be a code block), myReswill be disposed.

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

回答by Joseph Daigle

When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.

使用 ADO.NET 时,您可以将 keywork 用于诸如连接对象或读取器对象之类的内容。这样,当代码块完成时,它会自动处理您的连接。

回答by Joel Coehoorn

Things like this:

像这样的事情:

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

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

This SqlConnectionwill be closed without needing to explicitly call the .Close()function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.

SqlConnection将无需显式调用关闭.Close()功能,会出现这种情况,如果有异常抛出,甚至,而不需要一个try/ catch/ finally

回答by Gilligan

The Rhino Mocks Record-playback Syntaxmakes an interesting use of using.

犀牛嘲笑记录播放语法使一个有趣的使用using

回答by Grank

Thanks to the comments below, I will clean this post up a bit (I shouldn't have used the words 'garbage collection' at the time, apologies):
When you use using, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.
A bullet point here which will hopefully maybe get this un-markeddown: If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.

感谢下面的评论,我会把这篇文章清理一下(我当时不应该使用“垃圾收集”这个词,抱歉):
当你使用 using 时,它会调用对象上的 Dispose() 方法在使用范围的末尾。所以你可以在你的 Dispose() 方法中有很多很棒的清理代码。
这里有一个要点,希望可能会取消标记:如果您实现 IDisposable,请确保您在 Dispose() 实现中调用 GC.SuppressFinalize(),否则自动垃圾收集将尝试出现并在某些时候完成它点,如果您已经 Dispose()d ,这至少会浪费资源。

回答by MagicKat

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

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

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

回答by David Arno

"using" can also be used to resolve name space conflicts. See http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/for a short tutorial I wrote on the subject.

“using”还可用于解决名称空间冲突。请参阅http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/以获得我写的关于该主题的简短教程。

回答by David Basarab

The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.

using 关键字定义对象的作用域,然后在作用域完成时处理该对象。例如。

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

See herefor the MSDN article on the C# using keyword.

有关C# using 关键字的 MSDN 文章,请参见此处

回答by Bob Wintemberg

usingis used when you have a resource that you want disposed after it's been used.

当您有一个资源在使用后要处理时使用 using

For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.

比如你分配了一个 File 资源,只需要在一段代码中使用它进行一点点读或写, using 有助于在你完成后尽快处理 File 资源。

The resource being used needs to implement IDisposable to work properly.

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

Example:

例子:

using (File file = new File (parameters))
{
    *code to do stuff with the file*
}

回答by Joel Martinez

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

有趣的是,您还可以将 using/IDisposable 模式用于其他有趣的事情(例如 Rhino Mocks 使用它的其他方式)。基本上,您可以利用编译器始终对“已使用”对象调用 .Dispose的事实。如果您在某个操作之后需要发生某些事情……某些事情有明确的开始和结束……那么您可以简单地创建一个 IDisposable 类,该类在构造函数中启动操作,然后在 Dispose 方法中完成。

This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.

这允许您使用非常好的 using 语法来表示所述操作的显式开始和结束。这也是 System.Transactions 的工作原理。