簡體   English   中英

C# - 將 Switch 語句轉換為 If-Else

[英]C# - Convert Switch statement to If-Else

我在完成這項特定任務時遇到了一些麻煩。 獲取 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.");

通過這種方法,您可以擺脫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();

因此,在大多數編程語言中, switch語句和if-else語句幾乎是相同的(一般來說;對於某些語言的某些編譯器,switch 可能更快,尤其是我不確定 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

那有意義嗎?

我建議將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
};

那么您可以按如下方式使用它(兩個if s):

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.");
  ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM