combobox填充了枚举值,它应该切换到特定的情况,给出错误

本文关键字:情况 错误 出错 枚举 填充 combobox | 更新日期: 2023-09-27 18:07:33

区块报价这里定义了enum,

 enum emotion
        { verysad, sad, normal, happy, veryhappy }
        emotion em = emotion.verysad;
        emotion m = emotion.sad;
        emotion o = emotion.normal;
        emotion t = emotion.happy;
        emotion i = emotion.veryhappy;

private void button5_Click(object sender, EventArgs e)
        {
            string a = comboBox1.Text;   

Blockquotein这里,comboBox1是用枚举值填充的,当用户单击按钮时,它应该复制字符串a中的comboBox.text,然后切换到特定的枚举值并执行所需的解决方案,但无法执行相同的操作。

            switch (a)
            {
                case em:
                    { em++;
                    textBox5.Text = em.ToString();
                    }
                case m:
                    {
                        m++;
                        textBox5.Text = m.ToString();
                    }
                case o:
                    { o++;
                    textBox5.Text = o.ToString();
                    }
                case t:
                    {
                        t++;
                        textBox5.Text = t.ToString();
                    }
                case i:
                    {
                        textBox5.Text = i.ToString();
                    }
            }
        }

combobox填充了枚举值,它应该切换到特定的情况,给出错误

正如我的评论所问,不确定为什么要这样做。。。但在任何情况下,您都可以使用Enum.Parse来获取您的枚举。

var parsed_enum = (emotion)Enum.Parse(typeof(emotion), comboBox1.Text);
switch (parsed_enum) {
   // logic here
}

根据评论,您错过了break;。这是我的小提琴:

string txt; // used since I'm just mocking it, no real textbox in my code.
var parsed_enum = (emotion)Enum.Parse(typeof(emotion), s);
switch (parsed_enum) {  
    case emotion.verysad:  
            /*
             * m++ is rubbish? are you trying to cycle to the next emotion?
             * or is this some kind of counter?
             * In any case, since an enum is an int, you can just increment it whatever it is.
             * for example:
                var v = emotion.sad;
                v++;    // now v is emotion.normal.
             */
            // m++ 
            txt = em.ToString();
            break;  // You can have one without the curly brackets.
    case emotion.sad: { 
            txt = m.ToString();
            break; // or inside them
        }
    case emotion.normal:
        {
            txt = o.ToString();
            break;
        }
    // ...
}

组合框中的文本是一个字符串。假设它是一个包含枚举整数值的字符串,那么在switch语句中使用它之前,必须将它强制转换为emotion。。。

   switch ((emotion) Convert.ToInt32(a))
   {
       // ...
   }

组合框值可能是字符串"sad"、"normal"等。您可以像se:一样进行枚举解析

string a = comboBox1.Text;
string parsed = (emotion)Enum.Parse(typeof(emotion), a);
switch(parsed)
{
    ...
}