使用C#實現加減乘除算法常常被用做新手練習。本篇來分別體驗經過委託、接口、匿名方法、泛型委託來實現。
算法
加減乘除擁有相同的參數個數、類型和返回類型,首先想到了使用委託實現。ide
//建立一個委託 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 +")); }
以上,委託用在了方法層面。若是在類層面,也可用接口封裝加減乘除的共性。spa
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(""); } ...
委託還能夠結合匿名方法一塊兒使用。code
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(""); }
而用泛型委託實現更簡潔。blog
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(""); }
暫時這些。接口