使用的目的是什么?
DUPE:C# 中“using”的用法
我有看到人们使用以下内容,我想知道它的目的是什么? 是不是对象在被垃圾回收使用后就被销毁了?
例子:
using (Something mySomething = new Something()) {
mySomething.someProp = "Hey";
}
DUPE: Uses of "using" in C#
I have seen people use the following and I am wondering what is its purpose?
Is it so the object is destroyed after its use by garbage collection?
Example:
using (Something mySomething = new Something()) {
mySomething.someProp = "Hey";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用大致翻译为:
差不多就是这样。 目的是支持确定性处置,这是 C# 所不具备的,因为它是一种垃圾收集语言。 使用/处置模式为程序员提供了一种准确指定类型何时清理其资源的方法。
Using translates, roughly, to:
And that's pretty much it. The purpose is to support deterministic disposal, something that C# does not have because it's a garbage collected language. The using / Disposal patterns give programmers a way to specify exactly when a type cleans up its resources.
using 语句可确保即使在调用对象方法时发生异常,也会调用 Dispose()。
The using statement ensures that Dispose() is called even if an exception occurs while you are calling methods on the object.
using 语句的好处是,当您完成 using 块时,可以处理 () 中的所有内容。
The using statement has the beneficial effect of disposing whatever is in the () when you complete the using block.
当 < code>Something 类实现 IDisposable。 即使您在
using
块内遇到异常,它也可确保正确处理该对象。即,您不必仅调用
Dispose
来手动处理潜在的异常,using
块会自动为您完成此操作。它相当于:
You can use
using
when theSomething
class implements IDisposable. It ensures that the object is disposed correctly even if you hit an exception inside theusing
block.ie, You don't have to manually handle potential exceptions just to call
Dispose
, theusing
block will do it for you automatically.It is equivalent to this:
使用在编译时被翻译成
(在 IL 中也是如此)。
因此基本上您应该将它与实现
IDisposable
的每个对象一起使用。Using gets translated into
when compiling (so in IL).
So basically you should use it with every object that implements
IDisposable
.“using”块是一种保证在退出块时调用对象的“dispose”方法的方法。
它很有用,因为您可能会因中断、返回或异常而正常退出该块。
您可以使用“try/finally”执行相同的操作,但是“using”使您的意思更清楚,并且不需要在块之外声明的变量。
The 'using' block is a way to guarantee the 'dispose' method of an object is called when exiting the block.
It's useful because you might exit that block normally, because of breaks, because you returned, or because of an exception.
You can do the same thing with 'try/finally', but 'using' makes it clearer what you mean and doesn't require a variable declared outside th block.