C#-将Switch语句转换为If-Else
我在执行这项特殊任务时遇到了一些困难。获取switch语句并将其转换为if-else。该程序利用一个列表框来选择位置并显示相应的时区C#-将Switch语句转换为If-Else,c#,if-statement,listbox,switch-statement,C#,If Statement,Listbox,Switch Statement,我在执行这项特殊任务时遇到了一些困难。获取switch语句并将其转换为if-else。该程序利用一个列表框来选择位置并显示相应的时区 if (cityListBox.SelectedIndex != -1) { //Get the selected item. city = cityListBox.SelectedItem.ToString(); // Determine the time zone.
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
语句和if-else
语句几乎是同一个语句(一般来说,对于某些语言,在某些编译器上切换可能更快,尤其是C语言,我不确定)Switch
在语法上或多或少比if-else
更贴切。无论如何,与您的交换机对应的if-else语句如下所示:
if(城市==“檀香山”){
timeZoneLabel.Text=“夏威夷阿留申”;
}else if(城市=“旧金山”){
timeZoneLabel.Text=“太平洋”;
}否则,如果(城市=“丹佛”){
timeZoneLabel.Text=“Mountain”;
}
... 等
这有意义吗 通过这种方法,您可以摆脱
开关
或if-else
语句
创建一个类来表示时区
public class MyTimezone
{
public string City { get; set; }
public string Name { get; set; }
}
var selected = (MyTimeZone)cityListBox.SelectedItem;
timeZoneLabel.Text = selected.Name;
创建时区列表并将其绑定到列表框
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;
然后在要使用选定时区的代码中
public class MyTimezone
{
public string City { get; set; }
public string Name { get; set; }
}
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
?或timeZoneLabel.Text=s_TimeZones.GetValueOrDefault(cityListBox.SelectedItem.ToString(),“未知城市”)有什么问题
@trysomethingnew:开关
可能比如果
/否则
更快的原因是编译器可能决定最好将开关
编译成表驱动模式(可能使用字典
)。像Matt Kae一样,我不知道C#编译器是否能做到这一点,但如果不能做到,我会感到惊讶