InternalCancelHandler 是 delegate,这是 C# 保存对特定方法的引用的方式。第一行将委托定义为引用具有void 返回的方法,并且不接受任何参数(因为没有参数列表。)此定义:
delegate int InternalCancelHandler(bool boolParam);
定义一个委托,该委托将引用一个返回 int 并接受单个 bool 参数的方法。
下一行是该委托类型的静态只读字段的声明,它被初始化为引用DoConsoleCancelEvent 方法的新实例。
通过该声明,您现在可以通过调用委托来调用DoConsoleCancelEvent:
public static void CallDelegate()
{
// This line will actually call DoConsoleCancelEvent
MyType.cancel_handler();
}
请注意,委托类型末尾的 Handler 表明它是一个事件处理程序,这意味着您更有可能希望使用它来订阅事件:
public static void EventSub()
{
// This line makes it so that cancel_handler is called when
// SomeEvent is fired. Since cancel_handler actually refers
// to DoConsoleCancelEvent, it is *that* method that will
// actually be run
SomeType.SomeEvent += cancel_handler;
}
static 表示该字段与Type 相关联,而不是Type 的特定实例
readonly 表示该字段只能在 Type 的构造过程中分配