.NET - Replacing nested using statements with single using statement(.NET - 用单个 using 语句替换嵌套 using 语句)
问题描述
如果您遇到过类似这样的带有嵌套 using 语句/资源的 C# 代码:
If you came across some C# code like this with nested using statements/resources:
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var reader = new BinaryReader(responseStream))
{
// do something with reader
}
}
}
用这样的东西替换它安全吗?
Is it safe to replace it with something like this?
using (var reader = new BinaryReader(((HttpWebResponse)request.GetResponse()).GetResponseStream()))
{
// do something with reader
}
上面的例子只是嵌套的一次性资源的例子,如果使用不完全正确,请见谅.我很好奇当您处理最外层资源(在本例中为 BinaryReader)时,它是否会为您递归处理其子资源,或者您是否需要使用单独的 using 语句显式处理每个层"?例如.如果您处置 BinaryReader,它是否应该处置响应流,而后者又处置响应?考虑到最后一句话让我觉得您实际上确实需要单独的 using 语句,因为无法保证包装器对象会处理内部对象.是吗?
The example above is just an example of nested disposable resources, so forgive me if it's not exactly correct usage. I'm curious if when you dispose the outermost resource (the BinaryReader in this case), if it will recursively dispose its children for you, or if you need to explicitly dispose each "layer" with separate using statements? E.g. if you dispose the BinaryReader, is it supposed to dispose the response stream, which in turn disposes the response? Thinking about that last sentence makes me think you actually do need the separate using statements, because there's no way to guarantee that a wrapper object would dispose of the inner object. Is that right?
推荐答案
您需要单独的 using 语句.
You need the separate using statements.
在你的第二个例子中,只有 BinaryReader 会被释放,而不是用于构造它的对象.
In your second example, only the BinaryReader will get disposed, not the objects used to construct it.
要了解原因,请查看使用声明事实上.它需要您的第二个代码,并执行以下操作:
In order to see why, look at what the using statement actually does. It takes your second code, and does something equivalent to:
{
var reader = new BinaryReader(((HttpWebResponse)request.GetResponse()).GetResponseStream());
try
{
// do something with reader
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
}
如您所见,Response 或 ResponseStream 上永远不会有 Dispose() 调用.
As you can see, there would never be a Dispose() call on the Response or ResponseStream.
这篇关于.NET - 用单个 using 语句替换嵌套 using 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:.NET - 用单个 using 语句替换嵌套 using 语句
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
