.NET - 用单个 using 语句替换嵌套 using 语句
- 作者: 俺曾经叫仔仔
- 来源: 51数据库
- 2022-10-28
问题描述
如果您遇到过类似这样的带有嵌套 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.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
