如何减少if语句数量并高效重写对应业务逻辑代码?
优化方案
方案1:提取关键字复用逻辑
核心是先从Name里定位到匹配的数字关键字(One/Two/Three...),然后用同一套逻辑完成后续操作,直接消除分支判断。
代码实现
// 定义需要匹配的关键字列表,新增关键字直接加在这里就行 var targetKeywords = new[] { "One", "Two", "Three" }; // 从Name里找到第一个匹配的关键字 var matchedKeyword = targetKeywords.FirstOrDefault(key => Name.Contains(key)); if (matchedKeyword != null) { var checkIndex = Chart.YAxis.FindIndex(f => f.Index == index && f.Id.Contains(matchedKeyword)); axisIndex = AddAxis(checkIndex, axis); } else { // 无匹配时的处理逻辑 .... }
优势
- 代码量直接减半,新增关键字不用加新分支,维护成本极低
- 逻辑完全复用,避免重复代码带来的错误风险
方案2:字典映射扩展逻辑(适合后续需要差异化处理的场景)
如果之后不同关键字要执行不一样的逻辑,可以用字典把关键字和对应的处理方法绑定,同样能干掉if分支。
代码实现
// 初始化关键字与处理逻辑的映射关系 var keywordHandlers = new Dictionary<string, Func<int, Axis, int>> { ["One"] = (idx, ax) => { var checkIdx = Chart.YAxis.FindIndex(f => f.Index == idx && f.Id.Contains("One")); return AddAxis(checkIdx, ax); }, ["Two"] = (idx, ax) => { var checkIdx = Chart.YAxis.FindIndex(f => f.Index == idx && f.Id.Contains("Two")); return AddAxis(checkIdx, ax); }, ["Three"] = (idx, ax) => { var checkIdx = Chart.YAxis.FindIndex(f => f.Index == idx && f.Id.Contains("Three")); return AddAxis(checkIdx, ax); } }; // 查找匹配的关键字 var matchedKeyword = keywordHandlers.Keys.FirstOrDefault(key => Name.Contains(key)); if (matchedKeyword != null) { axisIndex = keywordHandlers[matchedKeyword](index, axis); } else { // 无匹配时的处理逻辑 .... }
优势
- 扩展性拉满,新增关键字只需要在字典里加一组键值对
- 不同关键字的逻辑相互隔离,代码结构更清晰
方案3:正则提取数字单词(适合关键字格式固定的场景)
如果Name的格式是「数字单词 + 后缀」(比如"One hundred"),可以用正则直接提取数字单词,不用手动维护关键字列表。
代码实现
// 匹配开头的数字单词,可根据实际需求扩展正则规则 var regex = new Regex(@"^(One|Two|Three)\s", RegexOptions.IgnoreCase); var match = regex.Match(Name); if (match.Success) { var matchedKeyword = match.Groups[1].Value; var checkIndex = Chart.YAxis.FindIndex(f => f.Index == index && f.Id.Contains(matchedKeyword)); axisIndex = AddAxis(checkIndex, axis); } else { // 无匹配时的处理逻辑 .... }
优势
- 不用手动维护关键字列表,适合关键字规则明确的场景
- 自动提取关键字,减少硬编码内容
内容的提问来源于stack exchange,提问作者Sarahrb
相关产品推荐
相关产品推荐

