簡體   English   中英

將方法傳遞給表單以供以后調用

[英]Passing methods to a form for later invokement

因此,我對如何將具有特定簽名的方法傳遞給表單感到困惑,該表單隨后可以使用其自己的參數調用該方法並評估返回值。 問題越多,我對委托,事件,事件處理程序,訂閱和Func and Actions的了解就越多。 (我嘗試了很多,修改了很多,但沒有用,但是我想那是因為我不了解它們的工作原理)我想做的事的例子:

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;
    }

}

那只是一個帶有方法執行某些操作的類,重要的是該方法將int作為參數並返回int。

現在出現了表單,因為我希望它可以工作..所以代碼不起作用:

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*/
    }

}

這些都不是什么“驚喜”,因為我對此感到沮喪,所以我想問問你們。

提前致謝!

-RmOL

自從我標記的答案被刪除以來,我將發布對我有用的內容。 感謝@Fabio提供解決方案。 (作為評論)


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

可以像其他任何類型一樣處理。 (在傳遞方法時,請勿在其后加上普通括號或與該方法有關的任何其他參數)

問題中顯示的示例如下所示:

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*/
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM