先看一段C的面向过程的函数指针代码:
int max(int x,int y)
{
return (x>y?x:y);
}
int min(int x,int y)
{
return(x<y?x:y);
}
int sub(int x, int y)
{
return(x+y);
}
int minus(int x,int y)
{
return(x-y);
}
void test(int (*p)(int,int),
int (*q)(int,int),
int a,
int b)
{
int Int1,Int2;
Int1=(*p)(a,b);
Int2=(*q)(a,b);
printf("%d,/t%d/n",Int1,Int2);
}
int main(int argc, _TCHAR* argv[])
{
test(max,min,10,3);
test(sub,minus,10,3);
return 0;
}
再看一段C#的代理代码:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
class MathClass
{
public static int max(int a, int b)
{
return (a > b ? a : b);
}
public static int min(int a, int b)
{
return (a < b ? a : b);
}
public static int sub(int a, int b)
{
return (a + b);
}
public static int minus(int a, int b)
{
return (a - b);
}
}
class Handler
{
public delegate int Calculation(int a, int b);
public static void EventHandler(Calculation c1,Calculation c2, int a, int b)
{
int x, y;
x = c1(a, b);
y = c2(a, b);
Console.WriteLine("{0}:{1}/n{2}:{3}",c1.Method.ToString(), x, c2.Method.ToString(),y);
}
}
class Program
{
static void Main(string[] args)
{
Handler.EventHandler(new Handler.Calculation(MathClass.max), new Handler.Calculation(MathClass.min), 10, 3);
Handler.EventHandler(new Handler.Calculation(MathClass.sub), new Handler.Calculation(MathClass.minus), 10, 3);
Console.ReadKey();
}
}
}