在c/c++中我们可以用函数指针。那在c#是不是也可以实现类似的功能呢?
答案是肯定的。我们可以在c#中用委托(delegate)来解决这个问题。
先看一段c/c++的函数指针代码:
#include <stdio.h>
int max(int x,int y)
{
return (x>y?x:y);
}
int min( int x, int y )
{
return(x<y?x:y);
}
void call( int (*fp)( int, int), int (*fq)( int, int), int x, int y)
{
printf( "%d,/t%d/n",(*fp)(x,y),(*fq)(x,y));
}
void main()
{
call(max,min,100,200);
getchar();
}
再看一段c#的代理代码:
using System;
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static int max( int x, int y)
{
return (x > y ? x : y);
}
static int min( int x, int y)
{
return (x< y ? x : y);
}
delegate int call( int x, int y);
static void EventHandler(call fp,call fq, int x, int y)
{
Console.WriteLine("{0}/n{1}", fp(x, y), fq(x, y));
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main( string[] args)
{
EventHandler( new call(max), new call(min), 100, 200);
//Console.ReadKey();
}
}
用c# delegate实现类似c/c++的函数指针,能有效简化代码并能提高函数的通用性。