2016-12-27 64 views
0

所以我对如何将具有特定签名的方法传递给表单然后可以使用其自己的参数调用所述方法并计算返回值的方法存在困惑。 这个问题,我对代理,事件,事件处理程序,订阅和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

+0

建设者'SomeForm(Func键 YourMethod )'应该工作。你能解释“不工作”是什么意思吗? – Fabio

+0

像传递方法的东西不工作,这就是它对我来说是多么的理想。 – RememberOfLife

回答

0

因为我标志着答案删除了,我会张贴我工作。 感谢@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*/ 
    } 

} 
相关问题