C#中如何把函数当做参数传递到别的函数中

【问题】

C#想要传递函数参数,但是参数类型是函数,不知道如何传递。

【解决过程】

1.找了半天,看到这里:把函数名作为参数传递–C#委托的声明和使用,说到用delegate,但是感觉有点复杂,而且不太像是能方便的解决此处的问题。

2.说实话,找了其他一些类似的帖子,还是没太看懂。

3. 不过最后还是自己在他们的描述的基础上,自己折腾出来了。

 

【总结】

将函数当做参数,传递到别的函数中,的确是通过代理实现的。

总体思路是:

1.先建一个delegate的函数,delegateFunc该函数的参数格式,要和你想要传递的那个函数funcToDelegate一致。即,参数个数,参数变量类型,顺序等都一样。

2.然后别的某个函数,比如beCalledFunction中,其参数,就可以支持带delegate类型的函数作为参数了。

3.然后你在另外的其他的地方,某个函数anotherFunc中,就可以调用该beCalledFunction函数,把原先的funcToDelegate当做参数一样,传递过去了。

通过例子,就很容易说明具体是如何操作的了:

 

原先代码如下:

void funcToDelegate(object sender, KeyPressedEventArgs e)
{
    // yyyyyyyyyyyyyyyy
}
 
private void anotherFunc(object sender, EventArgs e)
{
    //xxxxxxxxxx
     
    hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(funcToDelegate); // normal one: pass funcToDelegate into some other func
    hook.RegisterHotKey(controlKeys, key);
}
 

  

 

加了代理,使得可以将函数作为参数传递,变成了这样:

void funcToDelegate(object sender, KeyPressedEventArgs e)
{
    // yyyyyyyyyyyyyyyy
}
 
delegate void delegateFunc(object sender, KeyPressedEventArgs e); //(1) here para must same with the above function 'funcToDelegate', which is what you want to delegate, 's para
 
public void beCalledFunction(ModifierKeys_e paraA, Keys paraB, delegateFunc func) // (2) here para use that above delegate func as para
{
    hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(func);
    hook.RegisterHotKey(paraA, paraB);
}
 
private void anotherFunc(object sender, EventArgs e)
{
    //xxxxxxxxxx
    beCalledFunction(paraA, paraB, funcToDelegate); // (3) now can pass funcToDelegate to another func
}
 

  

 

posted @ 2017-12-21 17:07  fire909090  阅读(13361)  评论(0编辑  收藏  举报