C#使用语句的重点是什么?

发布于 2025-01-27 17:50:31 字数 286 浏览 2 评论 0原文

我不是在谈论对组件的引用,而是代码中的使用语句。

例如,这有什么区别:

using (DataReader dr = .... )
{
    ...stuff involving data reader...
}

这是什么:

{
    DataReader dr = ...

    ...stuff involving data reader...
}

当垃圾收集器出现时,数据标准肯定会被垃圾收集器清除吗?

I'm not talking about references to assemblies, rather the using statement within the code.

For example what is the difference between this:

using (DataReader dr = .... )
{
    ...stuff involving data reader...
}

and this:

{
    DataReader dr = ...

    ...stuff involving data reader...
}

Surely the DataReader is cleaned up by the garbage collector when it goes out of scope anyway?

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

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

发布评论

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

评论(2

迷爱 2025-02-03 17:50:32

使用语句的A 的点是,您使用该语句创建的对象隐含在块末尾处置。在您的第二个代码段中,数据读取器永远不会关闭。这是一种确保不再将一次性资源保留在要求的方法,即使抛出了例外,也将被释放。这是:

using (var obj = new SomeDisposableType())
{
    // use obj here.
}

在功能上等效:

var obj = new SomeDisposableType();

try
{
    // use obj here.
}
finally
{
    obj.Dispose();
}

您可以使用相同的范围对多个可一次性对象这样的范围:

using (var obj1 = new SomeDisposableType())
using (var obj2 = new SomeOtherDisposableType())
{
    // use obj1 and obj2 here.
}

如果您需要交织其他代码,例如

var table = new DataTable();

using (var connection = new SqlConnection("connection string here"))
using (var command = new SqlCommand("SQL query here", connection))
{
    connection.Open();

    using (var reader = command.ExecuteReader()
    {
        table.Load(reader);
    }
}

The point of a using statement is that the object you create with the statement is implicitly disposed at the end of the block. In your second code snippet, the data reader never gets closed. It's a way to ensure that disposable resources are not held onto any longer than required and will be released even if an exception is thrown. This:

using (var obj = new SomeDisposableType())
{
    // use obj here.
}

is functionally equivalent to this:

var obj = new SomeDisposableType();

try
{
    // use obj here.
}
finally
{
    obj.Dispose();
}

You can use the same scope for multiple disposable objects like so:

using (var obj1 = new SomeDisposableType())
using (var obj2 = new SomeOtherDisposableType())
{
    // use obj1 and obj2 here.
}

You only need to nest using blocks if you need to interleave other code, e.g.

var table = new DataTable();

using (var connection = new SqlConnection("connection string here"))
using (var command = new SqlCommand("SQL query here", connection))
{
    connection.Open();

    using (var reader = command.ExecuteReader()
    {
        table.Load(reader);
    }
}
ぇ气 2025-02-03 17:50:32

使用语句的此类自动处理在范围末尾获得的对象。

您可以参考此文档细节。

Such using statement automatically disposes the object obtained at the end of scope.

You may refer to this documentation for further details.

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