![](/img/trans.png)
[英]Cannot convert System.Threading.Tasks.Task… to System.Threading.Tasks.Task… despite seemingly being same type
[英]System.Threading.Tasks.Task`1[<myType>] being returned
这似乎是为什么异步函数返回System.Threading.Tasks.Task`1 [System.String]的副本。 但是我在做《答案》中建议的事情,但无济于事。
我正在运行控制台应用程序:
static void Main(string[] args)
{
...
var details = CallRestMethodAsync(url, filterObj);
Console.Write(details);
Console.ReadKey();
}
public static async Task<NotificationEvents> CallRestMethodAsync(string url, FilterPager filterPager = null)
{
...
var result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<NotificationEvents>(result, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}
当我在CallRestMethodAsync
的最后一行放置一个断点并检查result
,我发现它确实包含预期的对象。 而且,JsonConvert不会引发错误。
但是我得到的输出是:
System.Threading.Tasks.Task`1[NotificationsHandler.NotificationEvents]
更新(4/30/2019,11:09 CT):在接受@Martin Brown的回答后,我意识到我(愚蠢地)期望在控制台上看到我的类型输出的字符串化实例。 当然那是行不通的。 我需要在Main
内部做的是: var details = (CallRestMethodAsync(url, filterObj)).Result; // to force the Task to resolve to my type foreach (var result in details.Results) // Results being a (array) property Console.Write(details.Results[0].EventDate); // EventDate being a prop that the Console could actually output
var details = (CallRestMethodAsync(url, filterObj)).Result; // to force the Task to resolve to my type foreach (var result in details.Results) // Results being a (array) property Console.Write(details.Results[0].EventDate); // EventDate being a prop that the Console could actually output
您的CallRestMethodAsync
方法返回Task<NotificationEvents>
而不是预期的NotificationEvents
。 您可以将Main
方法设置为await
CallRestMethodAsync
的结果,如下所示:
static async Task Main(string[] args)
{
...
var details = await CallRestMethodAsync(url, filterObj);
Console.Write(details);
Console.ReadKey();
}
如果使用的是.net的旧版本,则可能无法创建异步main方法。 在这种情况下,您将需要获得以下任务的Result
:
static void Main(string[] args)
{
...
var details = CallRestMethodAsync(url, filterObj);
Console.Write(details.Result);
Console.ReadKey();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.