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);
...
这样有什么好处??
{
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);
...
这样有什么好处??
{
...
this.button1.Onclick += new System.EventHandler(this.button1_Onclick);
....private void button1_Onclick(...){...}
}Form1是不知道什么时候调用button1_Onclick()的,而Button知道,所以Form1就把这个方法委托给Button1,让Button调用他当然上面的例子是用事件,不过事件的本质是委托
有空去看看,可以很好的理解一下委托