什么是 C# Using 块,我为什么要使用它? [英] What is the C# Using block and why should I use it?

查看:39
本文介绍了什么是 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 块,我为什么要使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆