C#如何实现if/else if分支触发后统一执行的then公共代码块?
C# 没有内置你示例中提到的then关键字语法,以下是几种等价的实现方案,均可实现「任意if/else if分支命中后执行公共逻辑」的需求,避免重复编写list.Clear()这类重复代码:
方案1:使用布尔标记位(最通用易读)
这是最常用的实现方式,逻辑清晰无版本要求:
bool hasBranchExecuted = false; if (Red) { i -= 3; hasBranchExecuted = true; } else if (Yellow) { i -= 2; hasBranchExecuted = true; } // 等价于你需要的then块 if (hasBranchExecuted) { list.Clear(); } else { // 原else分支的逻辑写在这里 }
方案2:抽离分支逻辑为独立方法(适合复杂逻辑/复用场景)
如果分支处理逻辑比较复杂,或者多处需要用到相同的判断逻辑,可以把分支逻辑抽成独立方法,返回值表示是否有分支被命中:
// 抽离的分支处理方法 private bool TryHandleColorStatus(bool isRed, bool isYellow, ref int i) { if (isRed) { i -= 3; return true; } if (isYellow) { i -= 2; return true; } return false; } // 调用处代码 if (TryHandleColorStatus(Red, Yellow, ref i)) { list.Clear(); } else { // 原else分支逻辑 }
方案3:Switch 表达式写法(适合C# 8.0+版本)
如果你的项目使用C# 8.0及以上版本,可以用switch表达式实现更简洁的写法:
bool hasBranchExecuted = Red switch { true => () => { i -= 3; return true; }(), false when Yellow => () => { i -= 2; return true; }(), _ => false }; if (hasBranchExecuted) { list.Clear(); } else { // 原else分支逻辑 }
内容的提问来源于stack exchange,提问作者Leo Christensson
相关产品推荐
相关产品推荐

