- Example: Foo(+, 1, 2) = 3; Foo(*, 3, 6) = 18; Foo(/, 2, 4) = 0.5
- public class CStyle_Calculator
- {
- static public double Foo(char op, double x, double y)
- {
- switch(op)
- case ’+’: return x + y; break;
- case ’-’: return x - y; break;
- case ’*’: return x * y; break;
- case ’/’: return x / y; break;
- default: throw new Exception(”What the Hell you have input?");
- }
- }
- public interface I操作符 //谁说代码不能写中文的?恩恩
- {
- double 运算(double x, double y);
- }
- public class OO_Calculator
- {
- private I操作符 m_op;
- public OO_Calculator(I操作符 op)
- {
- this.m_op = op; //依赖注入【注2】
- }
- public double Foo(double x, double y)
- {
- return this.m_op.运算(x, y);
- }
- }
- public class 加法:I操作符
- {
- public double 运算(double x, double y)
- {
- return x + y;
- }
- }
- public class 减法:I操作符
- {
- public double 运算(double x, double y)
- {
- return x - y;
- }
- }
- public class 乘法:I操作符
- {
- public double 运算(double x, double y)
- {
- return x * y;
- }
- }
- public class 除法:I操作符
- {
- public double 运算(double x, double y)
- {
- return x / y;
- }
- }
- public class TheMainClass
- {
- static public void Main()
- {
- I操作符 我的加法 = new 加法();
- OO_Calculator 我的加法器 = new OO_Calculator(我的加法);
- double sum = 我的加法器.Foo(3, 4);
- System.Console.WriteLine(sum);
- //sum = 7
- //其他3个我就不废话了
- }
- }
- public delegate double TheOperator(double x, double y);
- public class Operators
- {
- static public double Add(double x, double y)
- {
- return x + y;
- }
- static public double Sub(double x, double y)
- {
- return x - y;
- }
- //乘,除法 我也懒得废话了
- }
- public class DotNet_Calculator
- {
- public double Foo(TheOperator op, double x, double y)
- {
- return op(x, y);
- }
- }
- public class TheMainClass
- {
- static public void Main()
- {
- TheOperator myAdd = new TheOperator(Operators.Add);
- TheOperator mySub = new TheOperator(Operators.Sub);
- DotNet_Calculator dc = new DotNet_Calculator();
- double sum = dc.Foo(myAdd, 2, 4); //sum = 6
- System.Console.WriteLine(sum);
- double sub = dc.Foo(mySub, 3, 7); //sub = -4
- System.Console.WriteLine(sub);
- }
- }
- (define (Foo op x y)
- (op x y))
- (define (Foo op x y)
- (op x y))