using(object obj = new Object()) 是什么意思?
这个语句在C#中意味着什么?
using (object obj = new object())
{
//random stuff
}
What does this statement means in C#?
using (object obj = new object())
{
//random stuff
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这意味着
obj
实现了IDisposible
并将在using
块之后被正确处理。它的功能与以下相同:It means that
obj
implementsIDisposible
and will be properly disposed of after theusing
block. It's functionally the same as:相当于:
Is equivalent to:
为什么它存在呢。
它存在于您关心其生命周期的类中,特别是当类在操作系统中包装资源并且您希望立即释放它时。否则,您将不得不等待 CLR 的(非确定性)终结器。
示例,文件句柄、数据库连接、套接字连接......
why does it exist tho.
It exists for classes where you care about their lifetime, in particular where the class wraps a resource in the OS and you want to release it immediately. Otherwise you would have to wait for the CLR's (non deterministic) finalizers.
Examples, file handles, DB connections, socket connections, ....
这是一种确定对象范围的方法,因此在退出时调用 dispose 方法。特别是对于数据库连接非常有用。如果对象未实现 idisposable,则会发生编译时错误
it is a way to scope an object so the dispose method is called on exit. It is very useful for database connections in particuler. a compile time error will occur if the object does not implement idisposable
using
确保在 using 块之后正确处置分配的对象,即使该块中发生未处理的异常也是如此。using
ensures the allocated object is properly disposed after the using block, even when an unhandled exception occurs in the block.