【问题标题】:C# - Convert Switch statement to If-ElseC# - 将 Switch 语句转换为 If-Else
【发布时间】:2020-02-08 20:22:56
【问题描述】:

我在执行这项特定任务时遇到了一些麻烦。采用 switch 语句并将其转换为 if-else。该程序利用列表框来选择位置并显示相应的时区。

if (cityListBox.SelectedIndex != -1)
        {
            //Get the selected item.
            city = cityListBox.SelectedItem.ToString();

            // Determine the time zone.
            switch (city)
            {
                case "Honolulu":
                    timeZoneLabel.Text = "Hawaii-Aleutian";
                    break;
                case "San Francisco":
                    timeZoneLabel.Text = "Pacific";
                    break;
                case "Denver":
                    timeZoneLabel.Text = "Mountain";
                    break;
                case "Minneapolis":
                    timeZoneLabel.Text = "Central";
                    break;
                case "New York":
                    timeZoneLabel.Text = "Eastern";
                    break;
            }
        }
        else
        {
            // No city was selected.
            MessageBox.Show("Select a city.");

【问题讨论】:

  • 到目前为止您尝试过什么? switch 有什么问题?

标签: c# if-statement listbox switch-statement


【解决方案1】:

通过这种方法,您可以摆脱 switchif-else 语句

创建一个类来表示时区

public class MyTimezone
{
    public string City { get; set; }
    public string Name { get; set; }
}

创建时区列表并将其绑定到列表框

var timezones = new[]
{
    new MyTimezone { City = "Honolulu", Name = "Hawaii-Aleutian" },
    new MyTimezone { City = "San Francisco", Name = "Pacific" },
    // and so on...
}   

cityListBox.DisplayMember = "City";
cityListBox.ValueMember = "Name"; 
cityListBox.DataSource = timezones;

然后在要使用选定时区的代码中

var selected = (MyTimeZone)cityListBox.SelectedItem;
timeZoneLabel.Text = selected.Name;

因为Name 属性用作ValueMember,所以您可以使用SelectedValue 属性。

// SelectedValue can bu null if nothing selected
timeZoneLabel.Text = cityListBox.SelectedValue.ToString();

【讨论】:

    【解决方案2】:

    因此,在大多数编程语言中,switch 语句和 if-else 语句几乎是相同的(一般而言;在某些语言的某些编译器上切换可能更快,我不确定特别是 C#)。 Switch 或多或少是 if-else 的语法糖。无论如何,与你的 switch 对应的 if-else 语句看起来像这样:

    if (city == "Honolulu") {
        timeZoneLabel.Text = "Hawaii-Aleutian";
    } else if (city == "San Francisco") {
        timeZoneLabel.Text = "Pacific";
    } else if (city == "Denver") {
        timeZoneLabel.Text = "Mountain";
    }
    ... etc
    

    这有意义吗?

    【讨论】:

    • @trysomethingnew:switch 可能比if/else 更快的原因是编译器可能决定最好将switch 编译成表驱动模式(可能使用Dictionary)。和 Matt Kae 一样,我不知道 C# 编译器是否会这样做,但如果没有,我会感到惊讶
    【解决方案3】:

    我建议将switch 变成Dictionary<string, string>,即单独的数据(城市及其时区)和表示LabelListBox 等。 ):

    private static Dictionary<string, string> s_TimeZones = new Dictionary<string, string>() {
      {"Honolulu", "Hawaii-Aleutian"},
      {"San Francisco", "Pacific"},
      //TODO: add all the pairs City - TimeZone here
    };
    

    那么你可以按如下方式使用它(两个ifs):

    if (cityListBox.SelectedIndex >= 0) {
      if (s_TimeZones.TryGetValue(cityListBox.SelectedItem.ToString(), out string tz))
        timeZoneLabel.Text = tz;
      else 
        timeZoneLabel.Text = "Unknown City";
    } 
    else {
      // No city was selected.
      MessageBox.Show("Select a city.");
      ...
    

    【讨论】:

    • timeZoneLabel.Text = s_TimeZones.GetValueOrDefault(cityListBox.SelectedItem.ToString(), "Unknown City")