1

匿名メソッドをインラインで割り当て、そのコード ブロック内でString、メソッド割り当ての直前に宣言されていた変数を割り当てようとしました。

その呼び出しで例外が発生しました。

NullReferenceException: オブジェクト参照がオブジェクトのインスタンスに設定されていません。

関連するコードは次のとおりです。

else
{
    String imagesDirectory = null;  // <-- produces NullReferenceException

    if (Version <= 11.05)
    {
        String message = "Continue with update?";
        DialogResult result = MessageBox.Show(message, "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
        {
            Boolean isValid = false;
            while (!isValid)
            {
                using (frmRequestName frm = new frmRequestName(true))
                {
                    frm.Text = "Select Directory";
                    frm.atbNameOnButtonClick += (s, e) =>
                    {
                        using (FolderBrowserDialog dlg = new FolderBrowserDialog())
                        {
                            dlg.Description = "Select the directory for image storage";
                            dlg.SelectedPath = "C:\\";
                            if (dlg.ShowDialog() == DialogResult.OK)
                                imagesDirectory = dlg.SelectedPath;  // <-- I think this is the root cause
                                //frm.EnteredName = dlg.SelectedPath;  // <-- this does NOT cause an exception...why?
                        }
                    };
                    if (frm.ShowDialog(null, Icon.FromHandle(SharedResources.Properties.Resources.OpenFolder_16x.GetHicon())) == DialogResult.OK)
                    {
                        isValid = ValidateImagesPath(imagesDirectory);
                    }
                }
            }
        }
        else
        {
            Cursor.Current = Cursors.Default;
            return false;
        }
    }
}

最初に、変数の割り当てによってimagesDirectory実際に例外がスローされます。しかし、匿名メソッド内でその変数を使用しているためだと思います。

誰かお願いします:

  1. 私の疑いを確認または反論する
  2. 正しい/間違っている理由を説明する
  3. コンパイラが独自のコンパイル時エラーをスローすることなくこれを可能にする理由を説明してください

PS - 匿名メソッド内の変数の使用法を別の変数に置き換えたところ、エラーはなくなりました。明らかに、根本的な原因については正しいのですが、その理由はまだわかりません...

この例では .NET 3.5 を使用しています。

編集:

メソッドの割り当ては次のとおりです...

public partial class frmRequestName : Form
{
    public EventHandler atbNameOnButtonClick;

    private void frmRequestName_Load(Object sender, EventArgs e)
    {
        atbName.OnButtonClick += atbNameOnButtonClick;  //this is a class that inherits from System.Windows.Forms.TextBox
    }
}
4

1 に答える 1

0

C# での匿名メソッド変数のスコープの兆候のようです。別のコンテキストで、匿名メソッドが外部で宣言された変数へのアクセスを保持していることを確認しましたか? 静的にしてみましたか?これは、真実への道をたどるのに役立つかもしれません (必ずしも素晴らしいコードではありません)。public static string imagesDirectory = string.Empty;

コンパイラは、コンパイル時に変数がスコープ内にあることを認識しますが、実行時のメソッドの実行は、クラス インスタンスのコンテキストでは匿名です。インスタンス変数は使用できないため、参照は null です。

于 2013-07-16T21:01:54.653 に答える