【问题标题】:How to pass async Task with parameters as a method argument?如何将带有参数的异步任务作为方法参数传递?
【发布时间】:2023-02-15 17:36:17
【问题描述】:

我有以下代码,但出现以下错误

第 21 行的第一个是“Delegate 'Func' does not take 2 arguments”

第 28 行的第二个是“参数 1:无法从 'System.Threading.Tasks.Task' 转换为 'System.Func<System.Threading.Tasks.Task>'”

我不知道我在这里做错了什么?

// Online C# Editor for free
// Write, Edit and Run your C# code using C# Online Compiler

using System;
using System.Threading.Tasks;
using System.Diagnostics; 

public class HelloWorld
{
    
async Task Print1(string a, string b)
{
    Debug.WriteLine("Printing!");
}

async Task PrintLoop(Func<Task> printer, int iterations = 3)
{
    for (int i = 0; i < iterations; i++)
    {
        string c = "1";
        await printer(c, c);
    }
}
    async Task Main()
    {
        string a ="";
        string b = "";
    await PrintLoop(Print1(a,b));
    }

}

【问题讨论】:

    标签: c# asynchronous delegates task


    【解决方案1】:

    Func&lt;Task&gt; 需要是 Func&lt;string, string, Task&gt;,因为您有两个 string 类型的参数和一个 Task 类型的返回值。

    看看overload Func&lt;T1, T2, TResult&gt; in the docs

    【讨论】:

      猜你喜欢
      • 2019-10-01
      • 1970-01-01
      • 2012-09-25
      • 2020-12-27
      • 2020-08-12
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多