C#下标索引问题,求解惑
为什么看代码注释
//下一首
private void btnnext_Click(object sender, EventArgs e)
{
count = 0;
SoundPlayer spPlay = new SoundPlayer();
//list.count 总共是23首歌曲
if (listBox1.SelectedIndex == list.Count - 1)//23//这里时下一首个,最后一首歌的时候,把索引赋值为-1
{
listBox1.SelectedIndex = -1;//为什么这下标赋值 -1 不会报错?下标不是非负数吗?
}
try
{
spPlay.SoundLocation = list[listBox1.SelectedIndex + 1];
string name = Path.GetFileName(list[listBox1.SelectedIndex + 1]);
label2.Text = name;
spPlay.Play();
count++;
listBox1.SelectedIndex = listBox1.SelectedIndex + 1;
}
catch
{
}
}
/// <summary>
/// 播放上一首
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLast_Click(object sender, EventArgs e)
{
count = 0;
//这里时上一首,我之前赋值listBox1.SelectedIndex == list.count; 会报错,原因超出下标.list.count总共是23个
//超过索引会 报错,为什么-1不报错呢?
SoundPlayer spPlay = new SoundPlayer();
if (listBox1.SelectedIndex == 0)
{
spPlay.SoundLocation = list[listBox1.SelectedIndex + list.Count - 1];
string name = Path.GetFileName(list[listBox1.SelectedIndex + list.Count - 1]);
label2.Text = name;
spPlay.Play();
count++;
listBox1.SelectedIndex = list.Count - 1;
}
else
{
try
{
spPlay.SoundLocation = list[listBox1.SelectedIndex - 1];
string name = Path.GetFileName(list[listBox1.SelectedIndex - 1]);
label2.Text = name;
spPlay.Play();
count++;
listBox1.SelectedIndex = listBox1.SelectedIndex - 1;
}
catch
{
}
}
}