最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#中如何把函数当做参数传递到别的函数中

C# crifan 7524浏览 0评论

【问题】

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
}

 

世上无难事,只怕之前人没有解释清楚,导致后来人看不明白。希望上述的解释,能让后来人看得明白。

转载请注明:在路上 » 【已解决】C#中如何把函数当做参数传递到别的函数中

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (2)

  1. 谢谢提醒,不过对C#不熟悉,action木有听过。。。。等有机会遇到类似问题了,再折腾吧。
    crifan12年前 (2012-06-28)回复
  2. 那你为什么不直接 传送 一个 Action 作为参数呢? delegate 还要单独声明 不如一个 泛型 的 Action 或者 Func 简洁。 这部分可以参考 函数式编程 的资料
    zwq0000012年前 (2012-06-28)回复
85 queries in 0.171 seconds, using 22.12MB memory