当匿名方法使用在别处声明的变量时,为什么会出现NullReferenceException?

时间:2013-06-28 13:15:05

标签: c# compilation .net-3.5

我在线分配了一个匿名方法,并且在该代码块中尝试分配一个在方法赋值之前声明的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. 解释为什么编译器可以在不抛出自己的编译时错误的情况下实现这一点
  4. P.S。 - 我用不同的变量替换了匿名方法中的变量用法,并且错误消失了。很明显,我对根本原因是正确的,但我仍然不知道为什么......

    我在这个例子中使用的是.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
        }
    }
    

1 个答案:

答案 0 :(得分:0)

似乎是C#中匿名方法变量作用域的症状。您是否在另一个上下文中验证了匿名方法是否保留对外部声明的变量的访你试过让它静止吗?这可能会帮助你走上真理的道路(虽然不一定是伟大的工作代码)。 public static string imagesDirectory = string.Empty;

编译器理解变量在编译时在范围内,但在运行时,该方法的执行在类实例的上下文中是匿名的。实例变量不可用,因此它的引用为null。