我刚刚发现和 C# 一样,VB.NET 也有 using
关键词。
直到现在我认为它没有它(愚蠢的我,我知道......)并做了这样的事情:
With New OleDbConnection(MyConnectionString)
' Do stuff
End With
与使用
using
相比,这样做有什么影响?像这样的声明Using cn as New OleDBConnection(MyConnectionString)
With cn
' Do stuff with cn
End With
End using
更新:
我应该补充一点,我熟悉什么
using
语句的作用在于它在构造退出时处理对象。但是,据我了解
With New ...
当对象超出范围时,构造将让对象将对象标记为准备好进行垃圾收集。所以我的问题真的是,与
using
的唯一区别是我会立即释放内存,而使用 With
构造它会在 GC 感觉时被释放吗?还是我在这里错过了更大的东西?是否有任何最佳实践影响?我应该去重写我用过的所有代码
With New MyDisposableObject() ... End With
如 Using o as New MyDisposableObject()
?
最佳答案
By using With...End With, you can perform a series of statements on a specified object without specifying the name of the object multiple times.
A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them.
托管资源由垃圾收集器处理,您无需进行任何额外编码。
您不需要使用 或 与 声明。
有时您的代码需要非托管资源。您有责任处理它们。 A 使用 块保证处置 当您的代码完成它们时,将调用对象上的方法。
关于vb.net - With... End With vs Using in VB.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15538438/