如何将嵌套三元运算符代码转换为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
相关产品推荐
相关产品推荐

