0

我想使用构造函数为我的类建立对象。问题是构造函数正确执行(在 Visual Studio 调试器中遍历构造函数中的每个赋值),但是在构造函数完成并建立对象后,我不能使用我的任何类的方法来访问数据成员。

构造函数上方列出的数据成员与构造函数内部分配的数据成员之间似乎存在脱节。

发布的错误是:“NullReferenceException Unhandled - 对象引用未设置为对象的实例。”

...
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.IO;

namespace ExcelManip
{
    class ExcelInterop
    {
        //MEMBERS
        private Application _excelApp;// = new Application();
        private Workbooks books;
        private Workbook workBook;

        //CONSTRUCTOR
        public ExcelInterop(string thisFileName)
        {
            Application _excelApp = new Application();
            Workbooks books = _excelApp.Workbooks;
            Workbook workBook  = books.Open(thisFileName,
                   Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                   Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                   Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                   Type.Missing, Type.Missing);
        }
4

1 回答 1

0

您在构造函数的范围内启动新变量,而不是在新对象实例的范围内。改成这样:

        public ExcelInterop(string thisFileName)
        {
            _excelApp = new Application();
            books = _excelApp.Workbooks;
            workBook  = books.Open(thisFileName,
                   Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                   Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                   Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                   Type.Missing, Type.Missing);
        }
于 2013-06-03T22:44:41.873 回答