简体   繁体   中英

Passing methods to a form for later invokement

So I have a confusion about how to pass a method with a specific signature to a form that then can invoke said method with its own parameters and evaluate the return value. The problem, the more I read about delegates, events, event-handlers, subscribing and Func and Actions .. the more I am confused. (I have tried lots of them, modified lots of them and non worked, but I suppose thats because I don't get how they work) Example of what I want to do:

public class WorkingStatic {

    public static SetUpForm() {
        SomeForm tmp_Form = new SomeForm(StaticMethod);
        /*somehow pass the method to the form so that it can invoke it*/
        tmp_Form.Show();
    }

    public static int StaticMethod(int p_Int) {
        // do whatever..
        return p_Int;
    }

}

That is just a class with a method that does something, important is the method takes an int as parameter and returns an int.

Now comes the Form as I would like it to work .. so code is not working:

public partial class SomeForm : Form {

    private Method m_Method;

    public SomeForm(/*here I pass a method*/Method p_Method) {
        InitializeComponent();
        m_Method = p_Method;
    }

    public void SomeMethodThatGetsCalledByAButton() {
        m_Method.Invoke(/*params*/ 1); /*would return 1*/
    }

}

None of this works 'what surprise', and because I am getting kind of frustrated about it I thought I'd ask you guys.

Thanks in advance!

-RmOL

Since the answer I marked got deleted I'll post what worked for me. Thanks to @Fabio for supplying the solution. (as a comment)


Func</*input types here with ',' in between*/, /*output type here*/>

can be handled like just any other type. (When passing the method do not put normal brackets or any other arguments concerning that method after it)

Example like shown in the question would then look like this:

public class WorkingStatic {

    public static SetUpForm() {
        SomeForm tmp_Form = new SomeForm(Func<int, int>(StaticMethod));
        /*pass the method to the form so that it can invoke it*/
        tmp_Form.Show();
    }

    public static int StaticMethod(int p_Int) {
        // do whatever..
        return p_Int;
    }

}

public partial class SomeForm : Form {

    private Func<int, int> m_Method;

    public SomeForm(Func<int, int> p_Method) {
        InitializeComponent();
        m_Method = p_Method;
    }

    public void SomeMethodThatGetsCalledByAButton() {
        m_Method(/*params*/ 1); /*would return 1*/
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM