C# 什么时候应该使用 using 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10057334/
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-09 12:17:05  来源:igfitidea点击:

When should I use the using Statement?

c#.netusing-statement

提问by JonHiggens

Possible Duplicate:
What is the C# Using block and why should I use it?

可能的重复:
什么是 C# Using 块,我为什么要使用它?

I'm converting an old site to C# and I'm not sure when I should be using 'using'. Are there any general guidelines? I know of the benefits, but I'm not 100% sure how to use it. Is it every time I 'new' a method/property?

我正在将旧站点转换为 C#,但不确定何时应该使用“使用”。有什么通用的指导方针吗?我知道这些好处,但我不是 100% 确定如何使用它。是不是每次我“新建”一个方法/属性?

SqlConnection awesomeConn = new SqlConnection(connection);

回答by Beachwalker

It is often used if you want to automatically dispose objects. Otherwise you have to call myobj.Dispose() manually.

如果要自动处理对象,通常会使用它。否则,您必须手动调用 myobj.Dispose()。

See the reference documentiation here: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

请参阅此处的参考文档:http: //msdn.microsoft.com/en-us/library/yh598w02.aspx

回答by rerun

Using is a convenience that allows you to assure that you can't exit a block with out disposing of the resource. It can and should be utilized whenever you have to utilize an IDisposable implementer in a local code block.

使用是一种便利,它允许您确保在不处理资源的情况下无法退出块。只要您必须在本地代码块中使用 IDisposable 实现器,就可以并且应该使用它。

回答by gdoron is supporting Monica

MSDN:

微软

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

通常,当您使用 IDisposable 对象时,您应该在 using 语句中声明并实例化它。using 语句以正确的方式调用对象上的 Dispose 方法,并且(当您按前面所示使用它时)它还会导致对象本身在调用 Dispose 时立即超出范围。在 using 块中,对象是只读的,不能修改或重新分配。

using 语句确保 Dispose 被调用,即使在您调用对象的方法时发生异常。您可以通过将对象放在 try 块中,然后在 finally 块中调用 Dispose 来获得相同的结果;事实上,这就是编译器如何翻译 using 语句。前面的代码示例在编译时扩展为以下代码(注意额外的大括号以创建对象的有限范围):

Example:

例子:

using (StreamReader stream = new StreamReader("path")) 
{
     string line = stream.ReadLine();
}

回答by Hymanson Pope

If a class implements IDisposablethen it will create some unmanaged resources which need to be 'disposed' of when you are finished using them. So you would do something like:

如果一个类实现,IDisposable那么它将创建一些非托管资源,当您使用它们时需要“处理”这些资源。所以你会做这样的事情:

SqlConnection awesomeConn = new SqlConnection(connection);

// Do some stuff

awesomeConn.Dispose();

To avoid forgetting to dispose of the resourses (in this case close the database connection), especially when an exception is thrown, you can use the usingsyntax to automatically call dispose when you go out of the using statement's scope:

为了避免忘记处理资源(在这种情况下关闭数据库连接),尤其是在抛出异常时,您可以使用using语法在超出 using 语句的作用域时自动调用 dispose:

using (SqlConnection awesomeConn = new SqlConnection(connection))
{
     // Do some stuff
} // automatically does the .Dispose call as if it was in a finally block

In fact, the using block is equivalent to:

实际上, using 块相当于:

try
{
    SqlConnection awesomeConn = new SqlConnection(connection);

    // do some stuff
}
finally 
{
    awesomeConn.Dispose();
}

回答by dkackman

Use using for all objects which you instantiate that implement IDisposable unless their lifetime extends beyond the current scope of execution (I.e. method call). In that case, for instance if you have a disposable member variable, then the containing class should implement IDisposable and Dispose members in its Dispose.

将 using 用于您实例化的所有实现 IDisposable 的对象,除非它们的生命周期超出当前执行范围(即方法调用)。在这种情况下,例如,如果您有一个一次性成员变量,那么包含类应该在其 Dispose 中实现 IDisposable 和 Dispose 成员。