在我的 C# 代码中,当我尝试定义 IEnumerable 任务的返回时,出现编译器错误 CS0029。我该如何纠正?

问题描述 投票:0回答:1

在我的以下 C# 代码中,定义 IEnumerable 任务的返回(代码的最后一行)时出现编译错误

编译器错误错误CS0029无法将类型“void”隐式转换为“System.Collections.Generic.IEnumerable

我应该如何更正我的代码?

private async ValueTask PingMachine() 
{
  var timesToPing = 4;
  var counter = 1;

  while (counter <= timesToPing) {
  var reply = await Pinger(counter);
  counter++;
  }
}

private async Task<IEnumerable<PingReply>> Pinger(int counter)
{
  List<string> addresses = new List<string>();
  if (Check_IP_Correct(TagService.IP_PLC_List) == true) 
  addresses.Add(TagService.IP_PLC_List);

  var tasks = addresses.Select(async ip =>
  {
  var result = await new Ping().SendPingAsync(ip, 1000));
  TagService.log_PLC.AppendLine($" Pinged {ip} {counter} times time:{result.RoundtripTime} status: {result.Status.ToString()}");
  });
  return await Task.WhenAll(tasks); // This line  I am getting the compiler error
}
c# return task ienumerable
1个回答
0
投票

看起来你的 lambda (

async ip => { ... }
) 没有返回任何内容。因此,它们只是类型
Task
,而不是您期望的
Task<PingReply>

要修复此问题,请将

return result;
添加到 lambda,或将
Pinger()
更改为返回
Task
,因为无论如何你都不使用结果。

© www.soinside.com 2019 - 2024. All rights reserved.