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

【已解决】通过Action或Func的形式实现函数当做参数传递的效果

C# crifan 4781浏览 0评论

【问题】

之前已经折腾成功了,C#中,将函数当做参数传递过去,不过用的是delegate:

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

参考某人评论,现在去实现对应的action或者是Func的版本。

 

【解决过程】

1.参考:

C# Passing Function as Argument

经过尝试,使用如下代码实现,Action<paras>的形式

 

//declaration and implementation of function
public void updateProgress(int percentage)
{
    pgbDownload.Value = percentage;
}

//call some other func, pass the function as parameter
getUrlRespStreamBytes(xxx, updateProgress);

//some other related function
public int getUrlRespStreamBytes(xxx, Action<int> funcUpdateProgress)
{
    //...
    
    if (funcUpdateProgress != null)
    {
        int currentPercent = 20;
        funcUpdateProgress(currentPercent);
    }
    
    //...
}

 

【总结】

  • 此处是当做参数要传递的函数没有返回值,所以可以用Action<paras>的形式;
  • 如果当做参数要传递的函数,是有返回值的话,就要改为Func<paras, returnValue>的形式了;

转载请注明:在路上 » 【已解决】通过Action或Func的形式实现函数当做参数传递的效果

发表我的评论
取消评论

表情

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

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

网友最新评论 (1)

    85 queries in 0.170 seconds, using 22.15MB memory