如何将委托作为参数传入

本文关键字:参数 | 更新日期: 2023-09-27 18:23:36

我想像这样动态地传递一个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,我尝试过使用"代理",但它不允许将其用作参数。

如何将委托作为参数传入

使用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();
}