namespace delegateDemo
{

public delegate void PrintCallback(int number); public class Printer
{
private PrintCallback _print; public PrintCallback PrintCallback
{
get{return _print;}
set{_print=value;}
}
} public class Driver
{
private void PrintInteger(int number)
{
Console.WriteLine("From PrintInteger:The number is {0} .",number);
} static void Main(string [] args)
{
Driver driver = new Driver();
Printer printer = new Printer();
printer.PrintCallback = new PrintCallback(driver.PrintInteger);
printer.PrintCallback(10);
printer.PrintCallback(100);
Console.WriteLine("Press Enter to exit ...");
Console.ReadLine();
}
}
}这个是<<ASP.NET服务器控件与组件开发>>上的例子,我想问下,Main函数里为什么要用:
printer.PrintCallback = new PrintCallback(driver.PrintInteger);
printer.PrintCallback(10);
printer.PrintCallback(100);
而不直接用:
driver.PrintInteger(10);
...
这样有什么好处??

解决方案 »

  1.   

    这只是书上举的例子,实际用的时候肯定不是这么用的,在实际应用中你的main函数是无法知道什么时候应该调用driver.print的。例如订阅按钮单击的事件class Form1 : System.Win.Forms.Form
    {
    ...
    this.button1.Onclick += new System.EventHandler(this.button1_Onclick);
    ....private void button1_Onclick(...){...} 
    }Form1是不知道什么时候调用button1_Onclick()的,而Button知道,所以Form1就把这个方法委托给Button1,让Button调用他当然上面的例子是用事件,不过事件的本质是委托
      

  2.   

    delegate本身就是一种数据类型,Lz只是简单的使用,感觉没必要放在一个类里去声明
      

  3.   

    说白了,最简单的理解delegate 就是C#的函数指针,只是比C++更好理解和使用了
      

  4.   

    http://blog.csdn.net/loverP/category/35262.aspx
    有空去看看,可以很好的理解一下委托
      

  5.   

    最好还是不要把Delegate和指针相提并论。指针是“功能上万能”的罪恶之源,因为它直接对应计算地址操作,而计算机全部操作也不过是地址操作和寄存器运算操作两种。这就像是一个人问“如何把电视台的节目搞好”的时候另外一个人回答“重新给每给人安排工作”一样。如果不知道指针有什么罪恶,也就不知道为什么需要使用恰当的面向对象方式来处理回调设计。