构造函数执行但成员仍然为null?

时间:2013-06-03 22:42:27

标签: c# constructor nullreferenceexception

我想使用构造函数为我的类建立对象。问题是构造函数正确执行(在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);
        }

1 个答案:

答案 0 :(得分: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);
        }