按要求退出Excel实例作为类成员

我试图创build一个类,我想用excel实例工作,我想要退出excel实例按要求(正如在这个答案中提到的。仍然能够正确debugging我分离垃圾收集器的方式如下:

Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim xlsInst As New ExcelInst GC.Collect() GC.WaitForPendingFinalizers() End Sub End Class Public Class ExcelInst Sub New() Dim myxlApp As New Excel.Application Dim myxlWb As Excel.Workbook '~~> Add a new Workbook myxlWb = myxlApp.Workbooks.Add '~~> Display Excel myxlApp.Visible = True myxlApp.Quit() End Sub End Class 

观察任务pipe理器,excel实例在窗体加载后立即退出。 但是我对class级不满意。 因为我想要有myxlAppmyxlWB私有variables。 但是,如果我改变我的课程

 Public Class ExcelInst Private myxlApp As New Excel.Application Private myxlWb As Excel.Workbook Sub New() '~~> Add a new Workbook myxlWb = myxlApp.Workbooks.Add '~~> Display Excel myxlApp.Visible = True myxlApp.Quit() End Sub End Class 

excel不再按需求closures。 任何人都知道为什么第一个片段工作(根据我的要求,第二个不是?

我会假设,因为在GC.Collect之前仍然有对xlsInst的引用,并且该对象包含对excel的引用,GC将不会收集。 尝试在收集之前做xlsInst = Nothing,也许在类中将variables设置为Nothing。

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim xlsInst As New ExcelInst xlsInst = Nothing GC.Collect() GC.WaitForPendingFinalizers() End Sub End Class Public Class ExcelInst Private myxlApp As New Excel.Application Private myxlWb As Excel.Workbook Sub New() '~~> Add a new Workbook myxlWb = myxlApp.Workbooks.Add '~~> Display Excel myxlApp.Visible = True myxlApp.Quit() myxlApp = Nothing myxlWb = Nothing End Sub End Class 

我必须补充一点,我发现在New()中有这个逻辑是很奇怪的。 我build议把它放在一个静态函数中,或者有一个.ProcessExcel()或.CloseExcel()函数。