C#中的delegate
2004-10-27 09:49 Jun1st 阅读(530) 评论(0) 编辑 收藏 举报c#中的委托类似于c和c++中的函数指针,使用委托可以将方法引用封装在委托对象内。然后可以将该委托对象传递给可调用所引用方法的代码,而不必在编译时知道将调用哪个方法。与 C 或 C++ 中的函数指针不同,委托是面向对象、类型安全的,并且是安全的。
委托声明定义一种类型,它用一组特定的参数以及返回类型封装方法。对于静态方法,委托对象封装要调用的方法。对于实例方法,委托对象同时封装一个实例和该实例上的一个方法。如果您有一个委托对象和一组适当的参数,则可以用这些参数调用该委托。
委托的一个有趣且有用的属性是,它不知道或不关心自己引用的对象的类。任何对象都可以;只是方法的参数类型和返回类型必须与委托的参数类型和返回类型相匹配。这使得委托完全适合“匿名”调用。
delegate void MyDelegate();
public class MyClass
{
public void InstanceMethod()
{
Console.WriteLine("A message from the instance method.");
}
static public void StaticMethod()
{
Console.WriteLine("A message from the static method.");
}
}
public class MainClass
{
static public void Main()
{
MyClass p = new MyClass();
// Map the delegate to the instance method:
MyDelegate d = new MyDelegate(p.InstanceMethod);
d();
// Map to the static method:
d = new MyDelegate(MyClass.StaticMethod);
d();
}
}
输出
A message from the instance method. A message from the static method