- Delegate是指向method的指针,其功能类似C++中的函数指针,但是C#中的delegate是type-safe的,只能指向签名相同的方法;在定义了delegate后,你可以通过+=来初始化并指向一个method。
class Controller
{
delegate void stopMachineryDelegate();
...
public Controller()
{
this.stopMachinery += folder.StopFolding;//void StopFolding()
//等效于this.stopMachinery = new stopMachineryDelegate(folder.stopFolding);
}
...
private stopMachineryDelegate stopMachinery; // Create an instance of the delegate
}
public void ShutDown()
{
this.stopMachinery();
...
}
- C#中的delegate可以同时指向多个method,这时调用delegate会自动调用被指向的每个method。
public Controller()
{
this.stopMachinery += folder.StopFolding;
this.stopMachinery += welder.FinishWelding;
this.stopMachinery += painter.PaintOff;
//可以使用-=从列表中去除method
this.stopMachinery -= folder.StopFolding;
}
- Anonymous method是没有名字的方法,主要用于向delegate添加签名不匹配的方法;可以有返回值,但是必须严格匹配delegate的类型;无法使用-=从列表中删除。
this.stopMachinery += delegate { folder.StopFolding(0); };
//Anonymous method也可以作为参数传递
control.Add(delegate { folder.StopFolding(0); } );
//Anonymous method也可以使用参数
control.Add(delegate(int param1, string param2) { /* code that uses param1 and param2 */... });
- 在.NET中,使用event来定义和触发信号动作,使用delegate来处理event发生时要采取的动作,delegate中指向的method称为subscriber。
class TemperatureMonitor
{
public delegate void StopMachineryDelegate();
public event StopMachineryDelegate MachineOverheating;
...
}
TemperatureMonitor tempMonitor = new TemperatureMonitor();
...
//和delegate一样,适用+=和-=来管理方法列表
tempMonitor.MachineOverheating += delegate { folder.StopFolding(0) };
tempMonitor.MachineOverheating += welder.FinishWelding;
tempMonitor.MachineOverheating += painter.PaintOff;
- Event可以像调用方法一样触发,触发前要检查是否为NULL
public delegate void Tick(int hh, int mm, int ss);
class Ticker
{
public delegate void Tick(int hh, int mm, int ss);
public event Tick tick;
...
...
private void Notify(int hours, int minutes, int seconds)
{
if (this.tick != null)
{
this.tick(hours, minutes, seconds);
}
}
...
}
- Events有内建的安全措施,public event只能在定义它的class内部被触发。
- System中定义的EventHandler delegate返回值为void,需要两个参数,一个指向触发这个event的object,一个EventArgs object包含附加的信息;大部分GUI控件的Event触发机制可以参看下面的例子。
namespace System
{
public delegate void EventHandler(object sender, EventArgs args) ;
public class EventArgs
{
...
}
}
namespace System.Windows.Forms
{
public class Control :
{
public event EventHandler Click;
...
}
public class Button : Control
{
...
}
}
class Example : System.Windows.Forms.Form
{
private System.Windows.Forms.Button okay;
...
public Example()
{
this.okay = new System.Windows.Forms.Button();
this.okay.Click += new System.EventHandler(this.okay_Click);
//等效于this.okay.Click += this.okay_Click;
...
}
private void okay_Click(object sender, System.EventsArgs args)
{
// Your code to handle the Click event
}
}
(待续,下一篇将主要描述C#中的泛型)
259

被折叠的 条评论
为什么被折叠?



