【问题标题】:Passing methods to a form for later invokement将方法传递给表单以供以后调用
【发布时间】:2016-12-27 17:30:17
【问题描述】:

所以我对如何将具有特定签名的方法传递给表单感到困惑,然后该表单可以使用自己的参数调用所述方法并评估返回值。 问题是,我对委托、事件、事件处理程序、订阅以及 Func 和 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

【问题讨论】:

  • SomeForm(Func<int, int> YourMethod) 的构造函数应该可以工作。你能解释一下“不工作”是什么意思吗?
  • 传递方法之类的东西不起作用,这对我来说是理想的。

标签: c# events delegates event-handling


【解决方案1】:

自从我标记的答案被删除后,我将发布对我有用的答案。 感谢@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*/
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    相关资源
    最近更新 更多