1. C# 中的委托类似于 C 或 C++ 中的函数指针。
2. 委托声明定义一种类型,它用一组特定的参数以及返回类型封装方法。
3. 委托的一个属性是,它不知道或不关心自己引用的对象的类。
一个简单的例子:
还有一个例子,是在博客上看到的,直贴其中主要的.
更详细的教程在:
http://cnblogs.com/minbear/articles/8808.aspx
2. 委托声明定义一种类型,它用一组特定的参数以及返回类型封装方法。
3. 委托的一个属性是,它不知道或不关心自己引用的对象的类。
一个简单的例子:
using System;
namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
///
//定义个新委托
delegate int Dec(int a,int b);
[STAThread]
static void Main(string[] args)
{
//实例化一个委托
Dec dec = new Dec(DeleDec);
//调用该委托
Console.Write(dec(50,20));
}
private static int DeleDec(int i,int j)
{
return (i - j);
}
}
}
namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
///
//定义个新委托
delegate int Dec(int a,int b);
[STAThread]
static void Main(string[] args)
{
//实例化一个委托
Dec dec = new Dec(DeleDec);
//调用该委托
Console.Write(dec(50,20));
}
private static int DeleDec(int i,int j)
{
return (i - j);
}
}
}
还有一个例子,是在博客上看到的,直贴其中主要的.
public delegate void ProcessBookDelegate(Book book);
public void ProcessPaperbackBooks(ProcessBookDelegate processBook)
{
foreach (Book b in list)
{
if (b.Paperback)
// Calling the delegate:
processBook(b);
}
}
// Create a new delegate object associated with the static
// method Test.PrintTitle:
bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(PrintTitle));
PriceTotaller totaller = new PriceTotaller();
// Create a new delegate object associated with the nonstatic
// method AddBookToTotal on the object totaller:
bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(totaller.AddBookToTotal));
public void ProcessPaperbackBooks(ProcessBookDelegate processBook)
{
foreach (Book b in list)
{
if (b.Paperback)
// Calling the delegate:
processBook(b);
}
}
// Create a new delegate object associated with the static
// method Test.PrintTitle:
bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(PrintTitle));
PriceTotaller totaller = new PriceTotaller();
// Create a new delegate object associated with the nonstatic
// method AddBookToTotal on the object totaller:
bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(totaller.AddBookToTotal));
更详细的教程在:
http://cnblogs.com/minbear/articles/8808.aspx