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

如何将嵌套三元运算符代码转换为IF结构?

三元表达式转IF结构的实现

下面是和你提供的三元表达式逻辑完全等价的IF结构代码:

string selectedCategoryId;

if (!string.IsNullOrEmpty(categoryId5))
{
    selectedCategoryId = categoryId5;
}
else if (!string.IsNullOrEmpty(categoryId4))
{
    selectedCategoryId = categoryId4;
}
else if (!string.IsNullOrEmpty(categoryId3))
{
    selectedCategoryId = categoryId3;
}
else if (!string.IsNullOrEmpty(categoryId2))
{
    selectedCategoryId = categoryId2;
}
else
{
    selectedCategoryId = categoryId1;
}

逻辑说明

这段代码从categoryId5开始依次检查:

  • 只要当前的categoryId不为空,就直接把它赋值给selectedCategoryId,并且停止后续判断
  • 如果前面的categoryId都为空,最后会默认使用categoryId1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:00:15