C# 消灭switch的面向映射编程
作者:互联网
原有switch写法,所有分支集中在一个方法中,使得方法过于冗长
class Calculator01 { public double Num1 { get; set; } public double Num2 { get; set; } public double Run(string operate) { switch(operate) { case "+": return Num1 + Num2; case "-": return Num1 - Num2; case "*": return Num1 * Num2; case "/": if (Num2 == 0) { throw new Exception("除数不能为0"); } return Num1 / Num2; default: throw new Exception("未知的操作符"); } } }
面向映射写法,将分支剥离为独立方法,避免主要方法过于冗长
class Calculator02 { // 内置委托Action、Func、Predicate的区别: // Action可以有多个参数但不可有返回值; // Func可以有多个参数且最后一个参数固定是返回值; // Predicate只能有1个参数且返回布尔值。 private Dictionary<string, Func<double, double, double>> map = new Dictionary<string, Func<double, double, double>>(); public double Num1 { get; set; } public double Num2 { get; set; } public Calculator02() { // 注册操作符到方法的映射 map.Add("+", Add); map.Add("-", Sub); map.Add("*", Mul); map.Add("/", Div); } public double Run(string operate) { if (!map.ContainsKey(operate)) throw new Exception("未知的操作符"); return map[operate](Num1, Num2); } private double Add(double num1, double num2) { return Num1 + Num2; } private double Sub(double num1, double num2) { return Num1 - Num2; } private double Mul(double num1, double num2) { return Num1 * Num2; } private double Div(double num1, double num2) { if (Num2 == 0) { throw new Exception("除数不能为0"); } return Num1 / Num2; } }
标签:map,return,映射,Num2,C#,double,switch,public,Num1 来源: https://www.cnblogs.com/lgyup/p/16685623.html