刚刚开始学习.net,学到delegate,很多书都介绍delegate的使用方法,其实delegate如何使用我会,但我不理解为何要使用delegate,什么时候用delegate,比如下面一个例子
public void add(int a, int b)
{Console.WriteLine("{0}+{1}={2}", a, b, a + b);}
public void sub(int a, int b)
{Console.WriteLine("{0}-{1}={2}", a, b, a - b);}
delegate void Mydelegate(int a,int b);
Mydelegate Adelegate;
string s = Console.ReadLine();
if (s == "a")
{ Adelegate = new Mydelegate(new math().add); }
else
{ Adelegate = new Mydelegate(new math().sub); }
Adelegate(5, 4);上面是委托来实现函数的调用,可为什么不直接引用函数呢?
if (s == "a")
{ new math().add(5, 4); }
else
{ new math().sub(5, 4); }