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 块,我为什么要使用它?


- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01