简体   繁体   English

c#中的using构造怎么样?

[英]What about the using construct in c#

I see this: 我看到了这个:

using (StreamWriter sw = new StreamWriter("file.txt"))
{
     // d0 w0rk s0n
}

Everything I try to find info on is does not explain what this doing, and instead gives me stuff about namespaces. 我尝试查找信息的所有内容都没有解释这是做什么的,而是给了我关于命名空间的东西。

You want to check out documentation for the using statement (instead of the using directive which is about namespaces). 您想查看using语句的文档(而不是有关命名空间的using指令 )。

Basically it means that the block is transformed into a try / finally block, and sw.Dispose() gets called in the finally block (with a suitable nullity check). 基本上它意味着将块转换为try / finally块,并在finally块中调用sw.Dispose() (使用适当的无效检查)。

You can use a using statement wherever you deal with a type implementing IDisposable - and usually you should use it for any disposable object you take responsibility for. 您可以在任何处理实现IDisposable的类型的地方使用using语句 - 通常您应该将它用于您负责的任何一次性对象。

A few interesting bits about the syntax: 关于语法的几个有趣的部分:

  • You can acquire multiple resources in one statement: 您可以在一个语句中获取多个资源:

     using (Stream input = File.OpenRead("input.txt"), output = File.OpenWrite("output.txt")) { // Stuff } 
  • You don't have to assign to a variable: 您不必分配给变量:

     // For some suitable type returning a lock token etc using (padlock.Acquire()) { // Stuff } 
  • You can nest them without braces; 你可以不用括号嵌套它们; handy for avoiding indentation 方便避免缩进

     using (TextReader reader = File.OpenText("input.txt")) using (TextWriter writer = File.CreateText("output.txt")) { // Stuff } 

The using construct is essentially a syntactic wrapper around automatically calling dispose on the object within the using. using构造本质上是一个语法包装器,可以自动调用使用中对象上的dispose。 For example your above code roughly translates into the following 例如,您的上述代码大致可转换为以下内容

StreamWriter sw = new StreamWriter("file.text");
try {
  // do work 
} finally {
  if ( sw != null ) {
    sw.Dispose();
  }
}

您的问题由规范的第8.13节回答。

Here you go: http://msdn.microsoft.com/en-us/library/yh598w02.aspx 在这里你去: http//msdn.microsoft.com/en-us/library/yh598w02.aspx

Basically, it automatically calls the Dispose member of an IDisposable interface at the end of the using scope. 基本上,它会在使用范围的末尾自动调用IDisposable接口的Dispose成员。

检查这个使用语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM