在对象上使用与不在对象上使用 C#

using on object vs not using it on object c#

在这种情况下“使用”的区别和好处是什么。 我将陈述两个类似的案例,请解释为什么在这种情况下我应该或不应该在我的 reader 之前使用“using”。

string manyLines = @"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";

using var reader = new StringReader(manyLines);
string? item;
do
{
    item = reader.ReadLine();
    Console.WriteLine(item);
} while (item != null);

string manyLines = @"This is line one
This is line two
Here is line three
The penultimate line is line four
This is the final, fifth line.";

var reader = new StringReader(manyLines);
string? item;
do
{
    item = reader.ReadLine();
    Console.WriteLine(item);
} while (item != null);
当提到 IDisposable.Dispose() 时,

using (thing) { ... } 只是 shorthand(大约)对于 try { ... } finally { thing?.Dispose(); }(还有一个异步孪生)。大多数 IDisposable 类型应该主动处理(例如)关闭文件、释放套接字等;对于 StringReader,这真的无关紧要(处置是 no-op),但是:无论如何也可以这样做。

我认为你应该检查这两个以前的答案

What are the uses of "using" in C#?

use of "using" keyword in c#

但简而言之,这不是“优势”问题,而是需求问题。 .NET 中的某些对象具有非托管资源(CLR 外部的资源,如数据库连接、套接字、OS 系统调用、OS API 等),这些资源必须手动处理,因为垃圾收集器确实不知道什么时候应该释放这些资源。因此,一旦您的执行流超出 using 块的范围,using 关键字和块就会处理该对象。

另请查看这些有关非托管资源的 Microsoft 文档

https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged

https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects

因为“stream”是非托管资源,如果不使用“using”,非托管资源会一直占用内存。

using是糖,IL代码是调用Stream对象的Dispose方法

当然,你也可以不调用“using”而调用“Dispose”方法; “reader.Dispose()”