匿名メソッドをインラインで割り当て、そのコード ブロック内で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
実際に例外がスローされます。しかし、匿名メソッド内でその変数を使用しているためだと思います。
誰かお願いします:
- 私の疑いを確認または反論する
- 正しい/間違っている理由を説明する
- コンパイラが独自のコンパイル時エラーをスローすることなくこれを可能にする理由を説明してください
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
}
}