标签:三元运算符 span stat set argument private opened read none
原文:减少if...的使用
最近维护一批代码,其中包括一堆if...的使用,多的情况嵌套8、9层,痛苦不堪,所以搜寻一些可以降低if...else的方法来改善一下代码,写个简单总结。
第一种:
优化前
if (measuredValue > 8) return 5 * measuredValue * measuredValue - 3; if (measuredValue > 4) return 4 * measuredValue - 2; if (measuredValue >= 0) return 3 * measuredValue - 1; return 2 * measuredValue;
使用列表和linq优化后(摘自:https://www.linkedin.com/pulse/if-less-programming-c-jiri-pokorny)
using System; using System.Linq; namespace ConsoleApp1 { internal class Program { private static readonly MeasureTransform[] Transformations = new MeasureTransform[] { // 这个顺序决定了判断先后顺序 new MeasureTransform(m => m > 8, m => 5 * m * m - 3), new MeasureTransform(m => m > 4, m => 4 * m - 2), new MeasureTransform(m => m >= 0, m => 3 * m - 1), new MeasureTransform(m => true, m => 2 * m) }; private static void Main(string[] args) { var executor = Transformations.First(t => t.CanApply(16)); Console.Write(executor.Transform(16)); } } internal class MeasureTransform { public MeasureTransform(Func<int, bool> canApply, Func<int, int> transform) { CanApply = canApply ?? throw new ArgumentNullException(nameof(canApply)); Transform = transform ?? throw new ArgumentNullException(nameof(transform)); } public Func<int, bool> CanApply { get; set; } public Func<int, int> Transform { get; set; } } }
第二种:使用逻辑运算符改善
using System; using System.Linq; namespace ConsoleApp1 { internal class Program { private static void Main(string[] args) { int a = 10; int b = 10; // 优化前 if (a > 5) { if (b > 10) { Console.Write(""); } } // 优化后 if (a > 5 && b > 10) { Console.Write(""); } } } }
第三种:从业务逻辑角度看看有没有多余的判断
using System; using System.Linq; namespace ConsoleApp1 { internal class Program { private static void Main(string[] args) { System.UInt32 a = 10; int b = (int)a + 10; // 优化前 if (a > 10) { if (b > 10) { Console.Write(""); } } // 优化后 if (a > 10) { Console.Write(""); } } } }
第四种:使用三元运算符
优化前
namespace ConsoleApp1 { internal class Program { private static void Main(string[] args) { System.UInt32 a = 10; uint c; if (a > 10) { c = a; } else { c = a + 10; } } } }
优化后
using System; using System.Linq; namespace ConsoleApp1 { internal class Program { private static void Main(string[] args) { System.UInt32 a = 10; int b = (int)a + 10; // 优化前 var c = a > 10 ? a : a + 10; } } }
第五种:太多if..else if...效率低,使用switch...case...,也好看点。
第六种:从架构层面使用依赖注入,反射之类的,参考https://www.c-sharpcorner.com/forums/how-can-i-remove-multiple-if-statement。
标签:三元运算符 span stat set argument private opened read none
原文地址:https://www.cnblogs.com/lonelyxmas/p/13046488.html