What does this declaration in C# .net mean?
I have the following declaration in .NET. I want to know what exactly this declaration mean (the second line), especially the DoConsoleCancelEvent
delegate void InternalCancelHandler;
static readonly InternalCancelHandler cancel_handler =
new InternalCancelHa开发者_运维问答ndler (DoConsoleCancelEvent);
The DoConsoleCancelEvent
is declared as:
internal static void DoConsoleCancelEvent{...}
What is the term used in .NET? Is it .NET reflection?
InternalCancelHandler
is a delegate
, which is the C# way of holding a reference to a particular method. The first line defines the delegate to refer to a method that has a void
return, and takes no parameters (since there is no parameter list.) This definition:
delegate int InternalCancelHandler(bool boolParam);
Defines a delegate that will refer to a method that returns an int
and accepts a single bool
parameter.
The next line is the declaration of a static, readonly field of that delegate type, which is initialized to a new instance referring to the the DoConsoleCancelEvent
method.
With that declaration, you can now call the DoConsoleCancelEvent
by invoking the delegate:
public static void CallDelegate()
{
// This line will actually call DoConsoleCancelEvent
MyType.cancel_handler();
}
Note that the Handler
at the end of the delegate type suggests that it is an event handler, which means it's more likely that you'd want to use it to subscribe to an event:
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
means that the field is associated with the Type
, and not a particular instance of the Type
readonly
means the field can only be assigned during construction of the Type
I believe the term you are looking for is Delegate.
In this case, InternalCancelHandler
is the delegate. The first line of code creates a delegate that points to your DoConsoleCancelEvent
method. The delegate will then be used to call your method at a later point in time.
InternalCancelHandler
is a delegate
.
According to a Mono commit, this is what it says about DoConsoleCancelEvent
:
Adds a call to the Win32 function SetConsoleCtrlHandler for Windows, which adds the DoWindowsConsoleCancelEvent wrapper for DoConsoleCancelEvent to the Ctrl-C handler when an event handler is added, and removes the handler once all event handlers are removed.
精彩评论