使用C#實現加減乘除算法經常被用作新手練習。本篇來分別體驗通過委托、接口、匿名方法、泛型委托來實現。
加減乘除擁有相同的參數個數、類型和返回類型,首先想到了使用委托實現。
//創建一個委托 public delegate decimal MathOperation(decimal left, decimal right); //創建方法參數和返回結果符合委托的定義 public static decimal Add(decimal left, decimal right) { return left + right; } public static decimal Subtract(decimal left, decimal right) { return left - right; } public static decimal Multiply(decimal left, decimal right) { return left * right; } public static decimal Divide(decimal left, decimal right) { return left / right; } //返回委托類型 private static MathOperation GetOperation(char oper) { switch(oper) { case '+': return Add; case '-': return Subtract; case '*': return Multiply; case '/': return Divide; } throw new NotSupportedException(""); } //封裝一個方法用來把操作數和符號考慮進來,返回委托類型 private static decimal Eval(string expr) { var elements = expr.Split(new []{' '}, 3); var left = Decimal.Parse(elements[0]); var right = Decimal.Parse(elements[1]); var ope = elements[2][0]; return GetOperation(op)(left, right); } void Main() { Console.WriteLine(Eval("1 3 +")); }
以上,委托用在了方法層面。如果在類層面,也可用接口封裝加減乘除的共性。
public interface IMathOperation { decimal Compute(decimal left, decimal right); } public class AddOperation : IMathOperation { decimal Compute(decimal left, decimal right) { return left + right; } } public class SubtractOperation : IMathOperation { decimal Compute(decimal left,, decimal right) { return left - right; } } public class MultiplyOperation : IMathOperation { decimal Compute(decimal left, decimal right) { return left * right; } } public class DivideOperation : IMathOperation { decimal Compute(decimal left, decimal right) { return left/right; } } //獲取接口類型 private static IMathOperation GetOperation(char oper) { switch(oper) { case '+': return new AddOperation(); case '-': return new SubtractOperation(); case '*': return new MultiplyOperation(); case '/': return new DivideOperation(); } throw new NotSupportedException(""); } ...
委托還可以結合匿名方法一起使用。
public delegate decimal MathOperation(decimal left, decimal right); private static MathOperation GetOperation(char oper) { switch(oper) { case '+': return delgate(decimal left, decimal right) {return left + right;}; case '-': return delgate(decimal left, decimal right) {return left - right;}; case '*': return delgate(decimal left, decimal right) {return left * right;}; case '/': return delgate(decimal left, decimal right) {return left / right;}; } throw new NotSupportedException(""); }
而用泛型委托實現更簡潔。
private static Func<decimal, decimal, decimal> GetOperation(char oper) { switch(oper) { case '+': return (left, right) => left + right; case '-': return (left, right) => left - right; case '*': return (left, right) => left * right; case '/': return (left, right) => left / right; } throw new NotSupportedExcepton(""); }
暫時這些。