【问题标题】:How do i pass in a delegate as a parameter我如何将委托作为参数传递
【发布时间】:2013-07-18 04:03:11
【问题描述】:

我想像这样动态地传入一个 void 或一个 int/string/bool(它返回一个值)。

Delay(MyVoid);//I wont to execute a delay here, after the delay it will execute the the param/void like so...
public static void MyVoid()
{
    MessageBox.Show("The void has started!");
}
public async Task MyAsyncMethod(void V)
{
    await Task.Delay(2000);
    V()
}

ps,我尝试过使用 Delegates,但它不允许将其用作参数。

【问题讨论】:

  • 以后不要重新提出问题,编辑您的原始问题。如果我在发布答案之前看到了这个问题,我会简单地投票关闭这个问题。就目前而言,我建议您删除您的其他问题。

标签: c# parameters delegates void


【解决方案1】:

使用 Action 委托来执行返回 void 的方法:

public async Task MyAsyncMethod(Action V)
{
    await Task.Delay(2000);
    V();
}

Func<T> 表示返回一些值的方法

public async Task MyAsyncMethod(Func<int> V)
{
    await Task.Delay(2000);
    int result = V();
}

【讨论】:

  • 另一个问题,我如何让公共异步任务返回一个整数?
  • 我需要 Task task3 = Task.Factory.StartNew(() => 作为异步工作
  • @DanielJones 我提供的链接包含一个非常好的、清晰的描述如何做到这一点。试试看,看看你是否可以自己解决,如果你仍然遇到问题,你可以在 SO 上提出一个新问题。
  • 别担心,我已经自己弄清楚了,谢谢你的帮助!
猜你喜欢
  • 2011-05-29
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
相关资源
最近更新 更多