繁体   English   中英

C#:switch语句有问题吗?

[英]C#: Problems with switch statement?

这是我的项目的代码,您可以在其中选择列表框中的项目,然后会弹出图片和说明。

        fruitBox = new ListBox();
        fruitImage = new PictureBox();

        fruitBox.Items.Add("Mangosteen");
        fruitBox.Items.Add("Bael");
        fruitBox.Items.Add("Coffee Berries");
        fruitBox.Items.Add("Jujube");
        fruitBox.Items.Add("Durian");

        string selectedFruit;


    }

    private void openButton_Click(object sender, EventArgs e)
    {
        string selectedFruit;
        selectedFruit = fruitBox.SelectedItem.ToString();

        if (fruitBox.SelectedIndex == -1)

        {
            selectedFruit = fruitBox.SelectedItem.ToString();

            switch (selectedFruit)
            {

                case "Mangosteen":
                    fruitImage.Image = imageList1.Images[0];
                    fruitDescription.Text = "Mangosteen description";
                    break;

                case "Bael":
                    fruitImage.Image = imageList1.Images[1];
                    fruitDescription.Text = "Bael description";
                    break;

                case "Durian":
                    fruitImage.Image = imageList1.Images[2];
                    fruitDescription.Text = "Durian description";
                    break;

                case "Coffee Berries":
                    fruitImage.Image = imageList1.Images[3];
                    fruitDescription.Text = "Coffee Berries description";
                    break;

                case "Jujube":
                    fruitImage.Image = imageList1.Images[4];
                    fruitDescription.Text = "Jujube description";
                    break;
            }
        }
        else
        {
            MessageBox.Show("Select a fruit");

但是,当我尝试运行它时,会弹出此消息:

“ Exotic Fruits.exe中发生了'System.NullReferenceException类型的未处理的异常。

附加信息:对象引用未设置为对象的实例。”

您应该在if语句之前删除此行:

selectedFruit = fruitBox.SelectedItem.ToString();

如果没有SelectedItem fruitBox.SelectedItem可能为null 。您正在检查SelectedIndex但是在尝试访问SelectedItem ,这会使if语句毫无意义 。您还可以像下面这样更改if语句:

if(fruitBox.SelectedItem != null)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM