What is the C# Using block and why should I use it?(什么是 C# Using 块,我为什么要使用它?)
问题描述
C# 中 Using 块的用途是什么?它与局部变量有何不同?
What is the purpose of the Using block in C#? How is it different from a local variable?
推荐答案
如果该类型实现了 IDisposable,它会自动释放该类型.
If the type implements IDisposable, it automatically disposes that type.
给定:
public class SomeDisposableType : IDisposable
{
...implmentation details...
}
这些是等价的:
SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}
using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}
第二个更容易阅读和维护.
The second is easier to read and maintain.
从 C# 8 开始,有一个 using 的新语法可能使代码更具可读性:
Since C# 8 there is a new syntax for using that may make for more readable code:
using var x = new SomeDisposableType();
它没有自己的 { } 块,使用的范围是从声明点到声明它的块的末尾.这意味着你可以避免像这样的东西:
It doesn't have a { } block of its own and the scope of the using is from the point of declaration to the end of the block it is declared in. It means you can avoid stuff like:
string x = null;
using(var someReader = ...)
{
x = someReader.Read();
}
还有这个:
using var someReader = ...;
string x = someReader.Read();
这篇关于什么是 C# Using 块,我为什么要使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是 C# Using 块,我为什么要使用它?
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
