有时我们需要将一个函数作为另一个函数的参数,这时就要用到委托(Delegate)机制。委托是一个较难讲清楚的概念,笔者苦思数日,终于想出了一个巧妙的例子。
下面我们设计一个马戏表演函数RunCircus(),它的第一个参数是代表动物的函数,传给它什么样的动物,就进行什么动物的表演。请新建一个名为“Delegate”的项目,然后添加如下代码 :
试一试:定义委托
//函数:狗表演
static void DogAct(string name) 
...{
Console.WriteLine("Hello,I am " + name + "!");
Console.WriteLine(@"
.----.
_.'__ `.
.--(#)(##)---/#\
.' @ /###\
: , #####
`-..__.-' _.-\###/
`;_: `''
.'''''''`.
/,Snoopy ,\
// COOL! \\
`-._______.-'
___`. | .'___
(______|______)");
}
//函数:猫表演
static void CatAct(string name) 
...{
Console.WriteLine("Hello,I am " + name + "!");
Console.WriteLine(@"
.-. __ _ .-.
| ` / \ |
/ '.()--\
| '._/
_| O _ O |_
=\ '-' /=
'-._____.-'
/`/\___/\`\
/\/o o\/\
(_| |_)
|____,____|
(____|____)");
}
//函数:狮子表演
static void LionAct(string name) 
...{
Console.WriteLine("Hello,I am " + name + "!");
Console.WriteLine(@"
,%%%%%%%%,
,%%/\%%%%/\%%
,%%%\c "" J/%%%
%. %%%%/ o o \%%%
`%%. %%%% _ |%%%
`%% `%%%%(__Y__)%%'
// ;%%%%`\-/%%%'
(( / `%%%%%%%'
\\ .' |
\\ / \ | |
\\/ ) | |
\ /_ | |__
(___________)))))))");
}
//定义委托
delegate void AnimalAct(string name);
//函数:马戏表演(第一个参数为AnimalAct型委托)
static void RunCircus(AnimalAct animalAct, string name) 
...{
animalAct(name);
}
static void Main(string[] args) 
...{
//把函数DogAct()转换为AnimalAct型委托
AnimalAct deleDogAct = new AnimalAct(DogAct);
//把委托deleDogAct传给函数RunCircus()
RunCircus(deleDogAct, "Snoopy");
//把函数CatAct()转换为AnimalAct型委托,并传给函数RunCircus()
RunCircus(new AnimalAct(CatAct), " Kitty ");
}





求定积分
//被积函数
static double F1(double x)

...{
return 2*x+1;
}
//被积函数
static double F2(double x)

...{
return x * x ;
}
//被积函数的委托
delegate double Integrand(double x);
//函数:定积分
static double DefiniteIntegrate(double a, double b, Integrand f)

...{
const int sect = 1000; //分割数目
double delta = (b - a) / sect;
double area = 0;
for (int i = 1; i <= 1000; i++)

...{
area += delta * f(a + i * delta);
}
return area;
}
//进行定积分运算
static void Main(string[] args)

...{
Integrand f1 = new Integrand(F1);
Integrand f2 = new Integrand(F2);
double result1 = DefiniteIntegrate(1, 5, f1);
double result2 = DefiniteIntegrate(0, 1, f2);
Console.WriteLine("result1 = ...{0}", result1);
Console.WriteLine("result2 = ...{0}", result2);
}