为什么我们在 C# 中将 using 放在 StreamReader 之前

发布于 2024-11-20 00:16:29 字数 350 浏览 1 评论 0原文

为什么我们在c#中把using放在streamreader之前

using (StreamReader sr = new StreamReader("TestFile.txt")) 
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}

why do we put using before streamreader in c#

using (StreamReader sr = new StreamReader("TestFile.txt")) 
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}

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

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

发布评论

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

评论(8

琉璃繁缕 2024-11-27 00:16:29

在处理一次性对象时,在 C# 中使用 block 非常方便。可处置对象是那些在调用处置时可以显式释放其使用的资源的对象。正如我们所知,.Net 垃圾收集是不确定的,因此您无法预测对象何时将被垃圾收集。

阅读这篇文章了解更多详细信息:理解 C# 中的“using”块

using block in C# comes very handly while dealing with disposable objects. Disposable objects are those objects that can explicitly release the resources they use when called to dispose. As we know .Net garbage collection is non-deterministic so you can’t predict when exactly the object will be garbage collected.

Read this post for more in details : understanding ‘using’ block in C#

穿越时光隧道 2024-11-27 00:16:29

这样,当您使用完 StreamReader 后,它就会被正确处理。此外,如果发生异常,using 语句会在异常传播出去之前调用 Dispose

So that when you are done using StreamReader it is disposed of properly. Also, in the event of an exception, the using statement calls Dispose before the exception propagates out.

贱人配狗天长地久 2024-11-27 00:16:29

每当您使用实现了 IDisposable 的对象(StreamReader 就是这样做的)时,最好使用 using 语法,因为它可以确保Dispose 方法总是被调用并且对象被正确处置。

例如,在这种情况下,将在文件“TestFile.txt”上获得各种句柄/锁,这可能会阻止其他人写入甚至读取该文件,直到处理掉流读取器或进程结束。其他对象(例如数据库对象)可能会耗尽数据库连接或网络资源,因此您应该在使用完对象后立即丢弃它们 - using 语句只是执行此操作时遵循的一种简单且安全的模式。

在幕后发生的事情与此类似(参考):

StreamReader sr = new StreamReader("TestFile.txt");
try
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}
finally
{
    if (sr != null)
    {
        ((IDisposable)sr).Dispose();
    }
}

但是using 语句比尝试手动处理 IDisposable 更简洁(并且更不容易出错)。

Its good practice to use the using syntax whenever you are working with an object that implements IDisposable, (which StreamReader does) as it ensures that the Dispose method always gets called and the object is properly disposed of.

For example in this case various handles / locks will be obtained on the file "TestFile.txt" that may prevent others from writing to or even reading this file until either the stream reader is disposed of or the process ends. Other objects (such as database objects) may use up database connections or network resources and so you should always dispose of objects as soon as you are done using them - the using statement is simply an easy and safe pattern to follow when doing this.

Under the covers whats happening is similar to this (reference):

StreamReader sr = new StreamReader("TestFile.txt");
try
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}
finally
{
    if (sr != null)
    {
        ((IDisposable)sr).Dispose();
    }
}

However the using statement is much cleaner (and less error prone) than attempting to dispose of the IDisposable by hand.

雨的味道风的声音 2024-11-27 00:16:29

如果没有using,文件在完成时不会被关闭。

Without using the file would not be closed when it was finished with.

睡美人的小仙女 2024-11-27 00:16:29

代码由编译器翻译为:

StreamReader sr = new StreamReader("TestFile.txt")
try
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}
finally
{
    sr.Dispose();
}

这确保无论发生什么,sr 都得到正确处理(清理)。每当创建实现 IDisposable 接口的对象时,最佳实践是将其包装在 using 构造中,以确保它被清理并尽快释放任何昂贵或稀缺的资源尽可能。

The code is translated by the compiler to:

StreamReader sr = new StreamReader("TestFile.txt")
try
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}
finally
{
    sr.Dispose();
}

This ensures that whatever happens, sr is properly disposed (cleaned up). Whenever an object is created that implements the IDisposable interface it is best practice to wrap it in a using construct to ensure it is cleaned up and releases any expensive or scarce resources as quickly as possible.

甜尕妞 2024-11-27 00:16:29

有时,在使用完对象后Dispose 很重要。

将对象的构造包装在 using 块中意味着一旦大括号内的代码完成,就会自动处理处理。

对于 StreamReader 读取文本文件的情况,这一点很重要,因为在 StreamReader 读取文件时文件被系统锁定。释放锁允许其他进程修改或删除该文件。

Sometimes it is important that we Dispose of objects after we have finished with them.

Wrapping the construction of an object in a using block means that the disposal is handled automatically as soon the code within the braces is completed.

In the case of a StreamReader reading a text file, this is important as the file is locked by the system while the StreamReader is reading it. Releasing the lock allows other processes to modify or delete the file.

z祗昰~ 2024-11-27 00:16:29

using 语句保证调用 Dispose() 方法,并且 Dispose() 调用 stream.Close()

using statement guaranteed that Dispose() method will be called, and Dispose() calls stream.Close()

小草泠泠 2024-11-27 00:16:29

您不需要使用 using,但这是绝对确定对象已正确处置的便捷方法。您可以在不使用 using 的情况下执行此操作,只要您确定始终在最后处理该对象(using a finally 是正常方式)。如果有特定原因想要进一步保留该对象,您可以这样做。

但是,如果您尝试执行此操作,则您的代码结构可能存在问题。将 StreamReader(和其他 iDisposible 对象)的使用包含在 using 语句中有助于更好地构建代码。

You don't need to use using, but it is a convenient way of being absolutely sure that the object is properly disposed of. You can do this without using, as long as you are certain that you always dispose of the object at the end ( using a finally is the normal way ). If there are specific reasons for wanting to persist the object further you can do this.

However, there is probaly something with your code structure if you are trying to do this. Encasing your use of StreamReader ( and other iDisposible objects ) in a using statement helps to structure your code well.

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