C# 中的委托类似于 C 或 C++ 中的函数指针。使用委托使程序员可以将方法引用封装在委托对象内。然后可以将该委托对象传递给可调用所引用方法的代码,而不必在编译时知道将调用哪个方法。与 C 或 C++ 中的函数指针不同,委托是面向对象、类型安全的,并且是安全的。
委托声明定义一种类型,它用一组特定的参数以及返回类型封装方法。对于静态方法,委托对象封装要调用的方法。对于实例方法,委托对象同时封装一个实例和该实例上的一个方法。如果您有一个委托对象和一组适当的参数,则可以用这些参数调用该委托。
委托的一个有趣且有用的属性是,它不知道或不关心自己引用的对象的类。任何对象都可以;只是方法的参数类型和返回类型必须与委托的参数类型和返回类型相匹配。这使得委托完全适合“匿名”调用。
下面简单的用几行代码来说明一下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace delegateDemo
{
delegate void MyDelegate(int x);
class MyClass
{
public static void Method1(int i)
{
Console.WriteLine("static void Method1:{0}",i);
}
public void Method2(int i)
{
Console.WriteLine("void Method2:{0}", i);
}
}
//声明的方法 method1 和method2 的参数必须和声明delegate 是一样才行。
class TestClass
{
static void Main()
{
//静态方法
MyDelegate delegate1 = new MyDelegate(MyClass.Method1); //当代用delegate1时,就会自动调用method1这个方法
//实例方法
MyClass class1 = new MyClass();
MyDelegate delegate2 = new MyDelegate(class1.Method2);
//另一个委托
MyDelegate delegate3 = new MyDelegate(delegate2);
delegate1(1);
delegate2(2);
delegate3(3);
}
}
}
/*
static void Method1:1
void Method2:2
void Method2:3
请按任意键继续. . .
*/