Brief analysis of steps for C to use delegation
- 2020-11-20 06:13:32
- OfStack
This article gives a brief analysis of the steps for C# to use delegation. Share to everybody for everybody reference. The specific analysis is as follows:
The delegate can be understood as C or C++ inside of the function pointer, calling the delegate is actually calling the delegate method.
The simple steps for using a delegate are as follows:
1. Define the delegate
// Define the delegate to use the keyword delegate
private delegate void SetProgressBarValueDelegate(int value);
2. State the delegate
private SetProgressBarValueDelegate setProgressBarValue;
3. Instantiate the delegate
setProgressBarValue = new SetProgressBarValueDelegate(SetProgressBarValue1);
SetProgressBarValue1 is the name of the method being delegated, and the parameter type is kept 1 to the type of the delegate. Its prototype is as follows:
// Set the progress bar 1 value
private void SetProgressBarValue1(int value)
{
pgProgressBar1.Value = value;
}
4. Use the delegate:
SetProgressBarValueMethod(setProgressBarValue);
// Set the progress bar value
private void SetProgressBarValueMethod(SetProgressBarValueDelegate setProgressBarValueDelegate)
{
for (int i = 1; i <= 100; i++)
{
Application.DoEvents();
Thread.Sleep(50);
setProgressBarValueDelegate(i);
}
}
/* This command tells the system to proceed with other user interface events to avoid faking death
* Is equivalent to Visual Basic 6.0 the DoEvents()
* Is equivalent to Easy language the Handle events () */
Application.DoEvents();
/* This command is used for thread pauses (argument: milliseconds)
* Used here in the main thread, this will cause a false death and pause just to get a better view */
Thread.Sleep(50);
Hopefully this article has helped you with your C# programming.