慕森王
假设您要编写一个过程,以在某个时间间隔[a,b] 上集成一些实值函数f(x)。假设我们要使用3点高斯方法来做到这一点(当然任何人都可以)。理想情况下,我们需要一些看起来像这样的函数:// 'f' is the integrand we want to integrate over [a, b] with 'n' subintervals.static double Gauss3(Integrand f, double a, double b, int n) { double res = 0; // compute result // ... return res;}因此,我们可以通过在任何Integrand,˚F,并获得其定积分在闭区间。到底应该Integrand是什么类型?没有代表好吧,没有委托,我们需要一种具有单个方法的接口,eval声明如下:// Interface describing real-valued functions of one variable.interface Integrand { double eval(double x);}然后,我们需要创建一整套实现此接口的类,如下所示:// Some functionclass MyFunc1 : Integrand { public double eval(double x) { return /* some_result */ ; }}// Some other functionclass MyFunc2 : Integrand { public double eval(double x) { return /* some_result */ ; }}// etc然后要在我们的Gauss3方法中使用它们,我们需要按以下方式调用它:double res1 = Gauss3(new MyFunc1(), -1, 1, 16);double res2 = Gauss3(new MyFunc2(), 0, Math.PI, 16);Gauss3的外观如下所示:static double Gauss3(Integrand f, double a, double b, int n) { // Use the integrand passed in: f.eval(x);}因此,我们需要做的所有事情只是在中使用我们的任意函数Guass3。与代表public delegate double Integrand(double x);现在,我们可以定义一些遵循该原型的静态(或非静态)函数:class Program { public delegate double Integrand(double x); // Define implementations to above delegate // with similar input and output types static double MyFunc1(double x) { /* ... */ } static double MyFunc2(double x) { /* ... */ } // ... etc ... public static double Gauss3(Integrand f, ...) { // Now just call the function naturally, no f.eval() stuff. double a = f(x); // ... } // Let's use it static void Main() { // Just pass the function in naturally (well, its reference). double res = Gauss3(MyFunc1, a, b, n); double res = Gauss3(MyFunc2, a, b, n); }}没有接口,没有笨拙的.eval东西,没有对象实例化,只是简单的函数指针(如用法)来完成简单的任务。当然,委托不只是幕后的函数指针,而且这是一个单独的问题(函数链接和事件)。