为什么这个Using()会给我一个错误?
我正在尝试打开一个(实际上数百个)Excel 文件。我打开应用程序,但想要在我打开的每个工作簿周围使用Using() 功能。为什么这会导致错误?
using (Excel.Workbook wbXL = appXL.Workbooks.Open(_sourceFullPath, Type.Missing, Excel.XlFileAccess.xlReadOnly))
{
//stuff with wbXL
}
using 得到红色下划线并显示“'Microsoft.Office.Interop.excel.Workbook':using 语句中使用的类型必须隐式转换为'System.IDisposable'。
如何使其工作?
I am trying to open an (hundreds actually) excel file(s). I open the application but want to use the Using() functionality around each of the workbooks I open. Why is this resulting in an error?
using (Excel.Workbook wbXL = appXL.Workbooks.Open(_sourceFullPath, Type.Missing, Excel.XlFileAccess.xlReadOnly))
{
//stuff with wbXL
}
using gets the red underline and says "'Microsoft.Office.Interop.excel.Workbook':Type used in a using statement must be implicitly convertible to 'System.IDisposable'.
How to make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
基本上就是它所说的 - 您只能将
using
与实现 IDisposable 的类一起使用,以便编译器在幕后知道在终结时调用哪个函数 -yourclass.Dispose()
。 Excel 互操作类不实现此功能。因此,您有两个选择:
为 Excel.Workbook 编写自己的包装类,该类实现 IDispose,并且公开对象本身以调用方法,或者也包装这些方法,例如
Implement
using
你自己,例如Pretty much what it says - you can only use
using
with classes that implement IDisposable, so that under the covers the compiler knows which function to call on finalisation -yourclass.Dispose()
. The Excel interop classes don't implement this.So you've got two choices:
Write your own wrapper class for Excel.Workbook that implements IDispose and either exposes the object itself to call methods on, or wraps those methods too, e.g.
Implement
using
yourself, e.g.using
语句中的任何项都必须实现IDisposable
接口。我手头没有文档,但我猜Excel.Workbook
没有实现此接口。Any item in a
using
statement must implement theIDisposable
interface. I haven't got the documentation to hand, but I'll guessExcel.Workbook
doesn't implement this interface.using 语句(C# 参考):
Excel.Workbook
未实现IDisposable
,因此您不能使用using
来实现它。using Statement (C# Reference):
Excel.Workbook
does not implementIDisposable
, so you can't useusing
for it..你无法让它发挥作用。
using
块用于尽可能快速、安全地从实现 IDisposable 接口的对象中释放资源。Excel.Workbook
未实现IDisposable
,因此您无法声明它在using
块中使用。You can't make it work.
The
using
block is used to free resources from objects that implement theIDisposable
interface as quickly and as safely as possible.Excel.Workbook
does not implementIDisposable
so you can't declare it for use in ausing
block.