c# - 使用:使用不好的做法?
那一年我读到了更多的内容,发现有一些不好的做法可以使用
using (some code) {
}
。有人可以向我解释一下所有这些不好的做法吗? 谢谢。
I have read more that year ago that there are a few bad practice to use
using (some code) {
}
. Could someone explain me all these bad practice?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么您认为这是一种不好的做法?这可能是一个非常好的(或最佳)实践,因为对象将在 using 块之后立即被处理。
Why do you think it's a bad practice? It can be a very good (or best) practice since the object will be disposed immediately after the using block.
不——这根本不是不好的做法——在许多情况下,这是非常好的做法。
使用“using”方法,您可以编写代码,知道
IDisposable
类型一旦超出范围就会自动释放,这意味着您无需手动调用Dispose()
在代码的每个出口点。话虽如此,您当然可能会想出一些
Dispose()
的糟糕用法,但它本质上并不是坏事,而且通常是好的。No - it isn't bad practice at all - in many cases it is extremely good practice.
Using the "using" approach, you can write code knowing that
IDisposable
types are automatically disposed of as soon as they go out of scope, meaning you don't need to manually callDispose()
at every exit point to your code.Having said that, you can certainly come up with some bad usages of
Dispose()
, but it is not intrinsically bad, and more often than not is good.