在 C# 中使用 using 语句

发布于 2024-07-14 18:15:17 字数 238 浏览 8 评论 0 原文

可能的重复:
什么是 C# using 块以及原因我应该使用它吗?

我看到代码块中间使用了 using 语句,这是什么原因?

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

I have seen the using statement used in the middle of a codeblock what is the reason for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

杯别 2024-07-21 18:15:17

using 语法可以(应该)用作定义任何实现 IDisposable。 using 语句确保在发生异常时调用 Dispose。

    //the compiler will create a local variable 
    //which will go out of scope outside this context 
    using (FileStream fs = new FileStream(file, FileMode.Open))
    {
         //do stuff
    }

或者,您可以使用:

    FileStream fs;
    try{
       fs = new FileStream();
       //do Stuff
    }
    finally{
        if(fs!=null)
           fs.Dispose();
    }

来自 MSDN 的额外阅读

C# 通过 .NET Framework 公共语言运行时 (CLR) 自动释放用于存储不再需要的对象的内存。 内存的释放是不确定的; 每当 CLR 决定执行垃圾回收时,就会释放内存。 但是,通常最好尽快释放有限的资源,例如文件句柄和网络连接。

using 语句允许程序员指定使用资源的对象何时应释放它们。 提供给 using 语句的对象必须实现 IDisposable 接口。 该接口提供了 Dispose 方法,该方法应该释放对象的资源。

The using syntax can(should) be used as a way of defining a scope for anything that implements IDisposable. The using statement ensures that Dispose is called if an exception occurs.

    //the compiler will create a local variable 
    //which will go out of scope outside this context 
    using (FileStream fs = new FileStream(file, FileMode.Open))
    {
         //do stuff
    }

Alternatively you could just use:

    FileStream fs;
    try{
       fs = new FileStream();
       //do Stuff
    }
    finally{
        if(fs!=null)
           fs.Dispose();
    }

Extra reading from MSDN

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

挽袖吟 2024-07-21 18:15:17

它通常在打开与流或数据库的连接时使用。

它的行为类似于 try { ... } finally { ... } 块。 在 using 块之后,括号中实例化的 IDisposable 对象将被正确关闭。

using (Stream stream = new Stream(...))
{


}

在这个例子中,流在块之后正确关闭。

It is often used when opening a connection to a stream or a database.

It behaves like a try { ... } finally { ... } block. After the using block, the IDisposable object that was instantiated in the parenthesis will be closed properly.

using (Stream stream = new Stream(...))
{


}

With this example, the stream is closed properly after the block.

樱花坊 2024-07-21 18:15:17

对于任何具有 IDisposable..(如 sqlconnection)的事物,使用的是 try finally 语法糖。 它的使用确保某些东西在超出 using(){} 范围后被处置。

using(SqlConnection conn = new SqlConnection(connString))
{
  //use connection
}

//shorter than

SqlConnection conn = new SqlConnection(connString)
try
{
  //use connection 
}
finally
{
    conn.Dispose();
}

using is try finally syntaxical suger for anything that has an IDisposable.. like a sqlconnection. Its use it make sure something is disposed after its out of the using(){} scope.

using(SqlConnection conn = new SqlConnection(connString))
{
  //use connection
}

//shorter than

SqlConnection conn = new SqlConnection(connString)
try
{
  //use connection 
}
finally
{
    conn.Dispose();
}
只是一片海 2024-07-21 18:15:17

using 语句确保对象在不再需要时得到正确处置。
它基本上可以节省您编写 obj.Dispose(); 的时间。 并提供有关变量的范围和用法的直观指南。

有关详细信息,请参阅MSDN 页面

The using statement ensures an object is properly disposed once it is nolonger required.
It basically saves you writing obj.Dispose(); and gives a visual guide as to the scope and usage of an variable.

See the MSDN page for more info

谁的新欢旧爱 2024-07-21 18:15:17

这种使用形式与释放资源有关。 它只能与实现 IDisposable 接口的类结合使用。

示例:

using(SqlConnection conn = new SqlConnection(someConnectionString))
{
     //Do some database stuff here
}

在 using 块的末尾调用 conn.Dispose,即使块内抛出了异常。 对于 SwqlConnection 对象意味着连接始终关闭。

这种结构的一个缺点是现在有办法知道发生了什么。

希望这有助于回答您的问题?

This form of using has to do with freeing resources. It can only be used in combination with class that implement the IDisposable interface.

example:

using(SqlConnection conn = new SqlConnection(someConnectionString))
{
     //Do some database stuff here
}

at the end of the using block conn.Dispose is called, even if an exception was thrown inside the block. In the case of a SwqlConnection object means that the connection is always closed.

A drawback of this construction is that there is now way of knowing what happend.

Hope this helps answer your question?

蓝眼睛不忧郁 2024-07-21 18:15:17

每当您的代码创建一个实现 IDisposable 的对象时,您的代码应该在 using 块内进行创建,如上所示。

这一规则有一个例外。 WCF 代理类设计中的错误导致 using 语句无法对代理类有用。 简而言之,代理类上的 Dispose 方法可能会引发异常。 WCF 团队认为没有理由不允许这样做。

不幸的是,看不到原因并不意味着没有原因:

try
{
    using (var svc = new ServiceReference.ServiceName())
    {
        throw new Exception("Testing");
    }
}
catch (Exception ex)
{
    // What exception is caught here?
}

如果隐式 Dispose 调用引发异常,则 catch 块将捕获该异常,而不是捕获异常。在 using 块中抛出一个。

Whenever your code creates an object that implements IDisposable, your code should do the creation inside a using block, as seen above.

There is one exception to this rule. An error in the design of WCF proxy classes prevents using statements from being useful for proxy classes. Briefly, the Dispose method on a proxy class may throw an exception. The WCF team saw no reason not to permit this.

Unfortunately, not seeing a reason doesn't mean that there is no reason:

try
{
    using (var svc = new ServiceReference.ServiceName())
    {
        throw new Exception("Testing");
    }
}
catch (Exception ex)
{
    // What exception is caught here?
}

If the implicit Dispose call throws an exception, then the catch block will catch that exception instead of the one thrown within the using block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文