功能之外的开关值?

Switch value outside of function?

我正在尝试获取在开关外部显示的值 alphabeta,但编译器抛出 编译器警告(级别 2)CS0162 (检测到无法访问的代码)。 非常感谢任何帮助。

        private void TestButton_Click(object sender, EventArgs e)
        {
            string alpha;
            byte beta = 0;

            alpha = comboBoxAlpha.Text;

            switch (alpha)
            {
                case "charlie":
                    beta = 1;
                    return;

                default:
                    beta = 0;
                    return;
            }

            if (beta == 0)
            {
                label1.Text = alpha;
            }
            else label1.Text = beta;
        }

不需要那么复杂的代码。据我所知,您希望在 "cahalie""1",否则 comboBoxAlpha.Text

private void TestButton_Click(object sender, EventArgs e) {
  if (comboBoxAlpha.Text == "charlie")
    label1.Text = "1";
}

甚至

private void TestButton_Click(object sender, EventArgs e) =>
  label1.Text = comboBoxAlpha.Text == "charlie" ? "1" : comboBoxAlpha.Text;

您的代码中的问题在 return 而不是 break 中:returns return 来自方法,当 break 刚刚打破 switch:

    private void TestButton_Click(object sender, EventArgs e)
    {
        string alpha;
        byte beta = 0;

        alpha = comboBoxAlpha.Text;

        switch (alpha)
        {
            case "charlie":
                beta = 1;
                break;    // Just break (jump out of) switch

            default:
                beta = 0;
                break;    // Just break (jump out of) switch 
        }

        if (beta == 0)
        {
            label1.Text = alpha;
        }
        else label1.Text = beta;
    }