zoukankan      html  css  js  c++  java
  • 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
    }
     
    

      

  • 相关阅读:
    python 读execl文件
    git 命令 个人备忘录
    python-django后端,富文本编辑器防XSS漏洞攻击,过滤富文本XSS
    mi
    Glance docker安装 cinder
    keystore glance
    openstack管理docker管理
    lvm 磁盘 数据库 wordpress 参考答案
    docker
    wordpress
  • 原文地址:https://www.cnblogs.com/fire909090/p/8081494.html
Copyright © 2011-2022 走看看