委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的使用可以像其他任何方法一样,具有参数和返回值.
声明的格式如下:
public
delegate
void
TestDelegate(
string
message);
委托概述
委托具有以下特点:
delegate 关键字用于声明一个引用类型,该引用类型可用于封装命名方法或匿名方法。委托类似于 C++ 中的函数指针;但是,委托是类型安全和可靠的。
委托是事件的基础。
通过将委托与命名方法或匿名方法关联,可以实例化委托。为了与命名方法一起使用,委托必须用具有可接受签名的方法进行实例化。为了与匿名方法一起使用,委托和与之关联的代码必须一起声明。
using
System;
// Declare delegate -- defines required signature:
delegate void SampleDelegate( string message);
class MainClass
... {
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
...{
Console.WriteLine(message);
}
static void Main()
...{
// Instantiate delegate with named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
SampleDelegate d2 = delegate(string message)
...{
Console.WriteLine(message);
};
// Invoke delegate d1:
d1("Hello");
// Invoke delegate d2:
d2(" World");
}
}
// Declare delegate -- defines required signature:
delegate void SampleDelegate( string message);
class MainClass
... {
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
...{
Console.WriteLine(message);
}
static void Main()
...{
// Instantiate delegate with named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
SampleDelegate d2 = delegate(string message)
...{
Console.WriteLine(message);
};
// Invoke delegate d1:
d1("Hello");
// Invoke delegate d2:
d2(" World");
}
}