How to use the C# MethodInvoker delegate?

The MethodInvoker delegate is a delegate with no parameters and no return value, which can be used to encapsulate a method and then call that method through the delegate.

Here is an example of using the MethodInvoker delegate:

using System;
using System.Windows.Forms;

public class Program
{
    public static void Main()
    {
        // 创建一个Form实例
        Form form = new Form();

        // 创建一个Button实例
        Button button = new Button();
        button.Text = "Click me";
        button.Click += new EventHandler(button_Click);

        // 将Button添加到Form中
        form.Controls.Add(button);

        // 使用MethodInvoker委托来封装一个方法,并通过委托来调用该方法
        MethodInvoker methodInvoker = new MethodInvoker(ShowMessage);
        methodInvoker.Invoke();

        // 显示Form
        Application.Run(form);
    }

    private static void button_Click(object sender, EventArgs e)
    {
        // 使用MethodInvoker委托来封装一个方法,并通过委托来调用该方法
        MethodInvoker methodInvoker = new MethodInvoker(ShowMessage);
        methodInvoker.Invoke();
    }

    private static void ShowMessage()
    {
        MessageBox.Show("Hello, World!");
    }
}

In the example above, we created an instance of a Form and added a Button to it. When the Button is clicked, the button_Click method is called. Inside the button_Click method, we use the MethodInvoker delegate to encapsulate a ShowMessage method and call it using the delegate. The ShowMessage method pops up a message box displaying “Hello, World!”.

Furthermore, we also use the MethodInvoker delegate in the Main method to directly call the ShowMessage method, demonstrating the usage of MethodInvoker.

bannerAds