当匿名方法使用在其他地方声明的变量时,为什么我会得到NullReferenceException

本文关键字:变量 为什么 NullReferenceException 声明 方法 方声明 其他 | 更新日期: 2023-09-27 18:20:12

我内联分配了一个匿名方法,并在该代码块中尝试分配一个在方法分配之前声明的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. 解释为什么编译器可以在不引发自己的编译时错误的情况下实现这一点

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
    }
}

当匿名方法使用在其他地方声明的变量时,为什么我会得到NullReferenceException

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

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