c#中Using块的目的是什么?它和局部变量有什么不同?
当前回答
如果该类型实现了IDisposable,它会自动释放该类型。
考虑到:
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);
}
第二种更容易阅读和维护。
自从c# 8以来,有了一个新的语法,可以使代码更具可读性:
using var x = new SomeDisposableType();
它没有自己的{}块,使用范围是从声明点到声明它的块的末尾。这意味着你可以避免这样的事情:
string x = null;
using(var someReader = ...)
{
x = someReader.Read();
}
还有这个:
using var someReader = ...;
string x = someReader.Read();
其他回答
如果该类型实现了IDisposable,它会自动释放该类型。
考虑到:
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);
}
第二种更容易阅读和维护。
自从c# 8以来,有了一个新的语法,可以使代码更具可读性:
using var x = new SomeDisposableType();
它没有自己的{}块,使用范围是从声明点到声明它的块的末尾。这意味着你可以避免这样的事情:
string x = null;
using(var someReader = ...)
{
x = someReader.Read();
}
还有这个:
using var someReader = ...;
string x = someReader.Read();
using (B a = new B())
{
DoSomethingWith(a);
}
等于
B a = new B();
try
{
DoSomethingWith(a);
}
finally
{
((IDisposable)a).Dispose();
}
using语句获取一个或多个资源,执行一条语句,然后处置资源。
从MSDN:
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible. The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
换句话说,using语句告诉. net一旦不再需要using块中指定的对象,就释放它。
在using块中放置代码可以确保一旦控件离开块,对象就会被处理(尽管不一定会被收集)。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本