委托(delegate),我就是不明白为什么要使用!我里面的这个程序不用委托就死人了啊?给我一个用委托的理由。
下面的程序可以不适用委托,直接调用类的方法就可以了。我知道这是举例子。但是,一般来说,为什么要使用委托呢?不适用委托,照样可以完成任务啊?比如下面的程序。谁解释一下,大白话最好。
using System;
class clsDelegate
{
public delegate int simpleDelegate (int a, int b);
public int addNumber(int a, int b)
{
return (a+b);
}
public int mulNumber(int a, int b)
{
return (a*b);
}
static void Main(string[] args)
{
clsDelegate clsDlg = new clsDelegate();
simpleDelegate addDelegate = new simpleDelegate(clsDlg.addNumber);
simpleDelegate mulDelegate = new simpleDelegate(clsDlg.mulNumber);
int addAns = addDelegate(10,12);
int mulAns = mulDelegate(10,10);
Console.WriteLine("Result by calling the addNum method using a delegate: {0}",addAns);
Console.WriteLine("Result by calling the mulNum method using a delegate: {0}",mulAns);
Console.Read();
}
}