0

我正在将音乐播放列表从磁盘加载到 C# ListView 控件。我使用 ListViewGroups 来分隔专辑,播放列表中可以有多个专辑。

播放列表以以下文本格式保存:(我知道这不是最好的方法,但适用于本示例)

|album|name of album
track 1 fsdfsfasf.mp3
track 2 fdsgfgfdhhh.mp3
track 3 gfdgsdgsdfgs.mp3

当我将播放列表加载到 ListView 时,我测试字符串是否为“|album|” 从行的开头找到,并将该行用于组标题文本。下面的代码示例:

using (StreamReader reader = File.OpenText("playlist.txt"))
{
    while (reader.Peek() >= 0)
    {
        result = reader.ReadLine();

        if (result.Substring(0, 7) == "|album|")
        {
            ListViewGroup group = new ListViewGroup();
            group.Header = result.Substring(7);
            lstPlaylist.Groups.Add(group); // lstPlaylist is existing ListView control for playlist
        }

        else
        {
            ListViewItem item = new ListViewItem(result, 0, group);
            lstPlaylist.Items.Add(item);
        }
    }
}

如果“|专辑|” 找到字符串,然后我创建新的 ListViewGroup。但是该组在 else 语句中是不可访问的(我无法将项目分配给组),因为它超出了范围。如何在 if 语句中创建新的 ListViewGroup 并在该 if 语句之外使用它?

4

3 回答 3

1

您需要在if语句之外声明变量,以便它在else子句中可用。您还需要处理在专辑之前找到曲目的情况,除非您已经验证了源文件。

using (StreamReader reader = File.OpenText("playlist.txt"))
        {
            ListViewGroup group = null;
            while (reader.Peek() >= 0)
            {
                result = reader.ReadLine();
                if (result.Substring(0, 7) == "|album|")
                {
                    group = new ListViewGroup();
                    group.Header = result.Substring(7);
                    lstPlaylist.Groups.Add(group); // lstPlaylist is existing ListView control for playlist
                }

                else
                {
                    if (group != null)
                    {
                        ListViewItem item = new ListViewItem(result, 0, group);
                        lstPlaylist.Items.Add(item);
                    } 
                    else
                    {
                        // you are trying to add a track before any group has been created.
                        // handle this error condition
                    }
                }
            }
        }
于 2014-06-23T18:19:32.103 回答
0

您必须首先在 if 语句之外声明变量,然后在 if 语句中为其赋予任何值。或者如果您希望 if 和 else 中的值相同,则在外部。

基本上发生的情况是,如果您转到代码的 else 部分,则永远不会生成该变量,因为它是在 if 部分中创建和初始化的。

祝你好运!

于 2014-06-23T18:10:36.387 回答
0

查看您的逻辑,您需要ListViewGroup在任何一种情况下进行初始化。如果您找到“|专辑|”这个词 然后您还分配一个属性值。因此,一个简单的解决方法是将变量向上移动以增加其范围:

ListViewGroup group = new ListViewGroup();//move to here
if (result.Substring(0, 7) == "|album|")
        {

            group.Header = result.Substring(7);
            lstPlaylist.Groups.Add(group); // lstPlaylist is existing ListView control for playlist
        }

        else
        {
            ListViewItem item = new ListViewItem(result, 0, group);//now group is initialized here as well
            lstPlaylist.Items.Add(item);
        }
于 2014-06-23T18:12:18.523 回答