C#中使用委托、接口、匿名方法、泛型委托实现加减乘除算法
使用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(""); }
暂时这些。