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 に答える