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;

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

于 2013-07-16T21:01:54.653 回答