You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#技术求助:如何将Switch语句转换为If-Else语句?

将Switch语句转换为If-Else语句的解决方案

没问题,这就帮你把这段switch逻辑转换成对应的if-else结构,保证功能和原代码完全一致:

if (cityListBox.SelectedIndex != -1) {
    // 获取选中项
    string city = cityListBox.SelectedItem.ToString();
    // 确定时区(转换为If-Else语句)
    if (city == "Honolulu") {
        timeZoneLabel.Text = "Hawaii-Aleutian";
    } else if (city == "San Francisco") {
        timeZoneLabel.Text = "Pacific";
    } else if (city == "Denver") {
        timeZoneLabel.Text = "Mountain";
    } else if (city == "Minneapolis") {
        timeZoneLabel.Text = "Central";
    } else if (city == "New York") {
        timeZoneLabel.Text = "Eastern";
    }
} else {
    // 未选择城市
    MessageBox.Show("Select a city.");
}

这里用else if的链式结构替代了原switch的case分支,每一个分支的判断逻辑和赋值操作都和原代码完全匹配,没有改动任何功能逻辑。如果之后需要新增城市时区的映射,只需要继续追加对应的else if分支即可,和原switch的扩展性一致。

内容的提问来源于stack exchange,提问作者tryingsomethingnew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:17:35