WTRBB 2021-11-17 13:11 采纳率: 50%
浏览 51
已结题

C#下标问题,求解惑,下标是非负数,我赋值-1不会报错

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
                {

                }

            }

        }
  • 写回答

2条回答 默认 最新

  • flybox0384 2021-11-17 14:08
    关注

    listBox1.SelectedIndex是listBox控件封装后的暴露出来的属性,赋值为-1是控件定义成无选择。
    list[n]的n是list的下标,list的下标从0 开始的,没有负值

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 11月25日
  • 已采纳回答 11月17日
  • 创建了问题 11月17日

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)