StackOverFlowException when mentioning ListBoxt?

本文关键字:ListBoxt mentioning when StackOverFlowException | 更新日期: 2023-09-27 18:08:01

当我点击buttonOpenAlbum并在AlbumListBox中选择一个项目时,我试图获得一个新表单(FormAlbum)打开。

如果我在buttonOpenAlbum_Click:

private void buttonOpenAlbum_Click(object sender, EventArgs e)
{
        FormAlbum MusicForm = new FormAlbum(this);
        MusicForm.ShowDialog();
}

新的from打开没有错误。然而,只要我提到"AlbumListBox"。SelectedItem"(如下面的代码FormMain),我得到一个"StackOverflowException是未处理的"在:

public ListBox AlbumListBox
{
    get
    { // <-This bracket here is where the error highlights

我不明白为什么我得到这个错误,只有它必须与AlbumListBox有关。我做错了什么?任何帮助都是感激的,谢谢。

FormMain形式:

public FormMain()
{
    InitializeComponent();
}
private void buttonAddAlbum_Click(object sender, EventArgs e)
{
    FormAlbumAC addAlbumForm = new FormAlbumAC(this);
    addAlbumForm.ShowDialog();
}
private void buttonOpenAlbum_Click(object sender, EventArgs e)
{
    if (AlbumListBox.SelectedItem != null)
    {
        MessageBox.Show(AlbumListBox.SelectedItem.ToString());
        FormAlbum MusicForm = new FormAlbum(this);
        MusicForm.ShowDialog();
    }
    else
    {
        MessageBox.Show("You need to select an album from the list to open.");
    }
}
public static class PublicVars
{
    public static List<Album> AlbumList { get; set; }
    static PublicVars()
    {
        AlbumList = new List<Album>(MAX_ALBUMS);
    }
}
public ListBox AlbumListBox
{
    get
    {
        return AlbumListBox;
    }
}

StackOverFlowException when mentioning ListBoxt?

看看你的属性实现:

public ListBox AlbumListBox
{
    get
    {
        return AlbumListBox;
    }
}

它只是递归地调用自己。如果将其转换为方法,可能会更容易看到:

public ListBox GetAlbumListBox()
{
    return GetAlbumListBox();
}

这就是为什么你有溢出。我不清楚你想要做什么…你期望价值来自哪里?您可能需要一个变量来支持该属性。您期望设置返回的值是什么?

我也强烈反对PublicVars类的设计。除了命名之外,您基本上是在使用全局变量——这不是一个好主意。确定哪些类需要访问数据,以及如何适当地将数据传递给它们。