在 C# 代码中使用 using 块有什么意义?
我看到大量具有以下语法的代码片段,
using (RandomType variable = new RandomType(1,2,3))
{
// A bunch of code here.
}
为什么不直接声明变量并使用它呢?
这种使用语法似乎只会使代码变得混乱并使其可读性降低。 如果该变量如此重要以至于只能在该范围内使用,为什么不将该块放入函数中呢?
I see loads of code snippets with the following Syntax
using (RandomType variable = new RandomType(1,2,3))
{
// A bunch of code here.
}
why not just declare the variable and use it?
This Using syntax seems to just clutter the code and make it less readable. And if it's so important that that varible is only available in that scope why not just put that block in a function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用有一个非常明确的目的。
它设计用于与实现 IDisposable 的类型一起使用。
在您的情况下,如果 RandomType 实现 IDisposable,它将在块末尾得到 .Dispose()'d。
Using has a very distinct purpose.
It is designed for use with types that implement IDisposable.
In your case, if RandomType implements IDisposable, it will get .Dispose()'d at the end of the block.
与以下内容几乎相同(有一些细微的差异):
请注意,在调用“Using”时,您可以将任何内容强制转换为 IDisposable:
finally 中的 null 检查将捕获任何实际上未实现 IDisposable 的内容。
is pretty much the same (with a few subtle differences) as:
Note that when calling "Using", you can cast anything as IDisposable:
The null check in the finally will catch anything that doesn't actually implement IDisposable.
不,它不会使您的代码变得混乱,或使其可读性降低。
using 语句只能用于 IDisposable 类型(即实现 IDisposable 的类型)。
通过在 using 块中使用该类型,当 using 块的范围结束时,将使用该类型的 Dispose 方法。
因此,请告诉我哪些代码对您来说可读性较差:
或者
No, it does not clutter your code , or make it less readable.
A using statement can only be used on IDisposable types (that is, types that implement IDisposable).
By using that type in a using - block, the Dispose method of that type will be used when the scope of the using-block ends.
So, tell me which code is less readable for you:
or
using 语句中使用的对象必须实现 IDisposable,因此在作用域结束时,可以保证调用 Dispose(),因此理论上,您的对象应该在此时被释放。 在某些情况下,我发现它使我的代码更加清晰。
An object being used in a using statement must implement IDisposable, so at the end of the scope, you're guaranteed that Dispose() will be called, so theoretically, your object should be released at that point. In some cases, I've found it makes my code clearer.
using 关键字提供了一种确定性的方法来清理对象分配的托管或非托管资源。 如果不使用 using 关键字,则在完成该对象后,您有责任调用 Dispose() (或在某些情况下,调用 Close())。 否则,资源可能直到下一次垃圾回收才被清理干净,甚至根本没有清理干净。
The using keyword provides a deterministic way to clean up the managed or unmanaged resources that an object allocates. If you don't use the using keyword, you are responsible to call Dispose() (or in some cases, Close()) when finished with that object. Otherwise, the resources may not be cleaned up until the next garbage collection, or even not at all.
根据MSDN,以下
使用
code:扩展为:
它确实不会让你的代码变得混乱。 实际上恰恰相反!
According to MSDN, the following
using
code:expands to this:
And it does really not clutter your code. Quite the opposite actually!