为什么会出现这种使用()给我一个错误? [英] Why does this Using() give me an error?

查看:207
本文介绍了为什么会出现这种使用()给我一个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想(实际上是上百个)打开一个Excel文件(S)。我打开应用程序,但要使用围绕每个我打开工作簿的使用()功能。这是为什么造成错误?

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
}

使用得到红色下划线并说:'Microsoft.Office.Interop.excel.Workbook:在使用语句中使用的类型必须是隐式转换为System.IDisposable的

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'.

如何使这项工作。

推荐答案

差不多它说什么? - 你只能使用使用与实现IDisposable,类,以便在编译器知道井盖其中的函数,在定稿调用 - yourclass.Dispose() Excel的互操作类没有实现这个

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.

所以,你有两个选择:


  1. 写出Excel.Workbook实现IDispose,要么公开对象本身来调用方法,或者包装这些方法太,如:

  1. 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.

public class DisposableWorkbook : IDisposable
{
    private Excel.Workbook _workbook = null;

    public DisposableWorkbook(Excel.Application appXL, String path,
                              NotSureOfType otherArgument,
                              Excel.XlFileAccess access)
    {
        _workbook = appXL.Workbooks.Open(path, otherArgument, access);
    }

    public Excel.Workbook Workbook
    {
        get { return _workbook; }
    }

    public void Dispose()
    {
        if (workbook != null)
        {
            workbook.Close(Excel.XlSaveAction.xlDoNotSaveChanges,
                           workbookToClose);
            workbook = null;
        }
    }
}

using (DisposableWorkbook dwbXL = new DisposableWorkbook(appXL,
          _sourceFullPath, Type.Missing, Excel.XlFileAccess.xlReadOnly))
{
     Excel.Workbook wbXL = dwbXL.Workbook;
     // stuff with wbXL
}


  • 实施<$ C的东西$ C>使用自己,如:

    Excel.Workbook wbXL = null;
    try
    {
        wbxl = appXL.Workbooks.Open(_sourceFullPath, Type.Missing,
                                    Excel.XlFileAccess.xlReadOnly);
        //stuff with wbXL
    }
    finally
    {
        if (wbxl != null) wbxl.Close();
    }
    


  • 这篇关于为什么会出现这种使用()给我一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆