gpt4 book ai didi

c# - 无法从 Task<> 隐式转换类型

转载 作者:太空宇宙 更新时间:2023-11-03 15:03:12 25 4
gpt4 key购买 nike

我正在尝试掌握 .NET 4.5 中的异步方法语法。我以为我已经完全理解了这些示例,但是无论异步方法的类型是什么(即 Task<T> ),我总是在转换回 T 时得到相同类型的错误错误。 - 我知道这几乎是自动的。以下代码产生错误:

Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' to 'System.Collections.Generic.List<int>'

public List<int> TestGetMethod()
{
return GetIdList(); // compiler error on this line
}


async Task<List<int>> GetIdList()
{
using (HttpClient proxy = new HttpClient())
{
string response = await proxy.GetStringAsync("www.test.com");
List<int> idList = JsonConvert.DeserializeObject<List<int>>();
return idList;
}
}

如果我也显式转换结果,它会失败。这:

public List<int> TestGetMethod()
{
return (List<int>)GetIdList(); // compiler error on this line
}

某种程度上可以预见会导致此错误:

Cannot convert type 'System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' to 'System.Collections.Generic.List<int>'

非常感谢任何帮助。

最佳答案

您的示例的主要问题是您无法隐式转换 Task<T>向基类返回类型 T类型。您需要使用 Task.Result 属性。请注意,Task.Result 将阻止异步代码,应谨慎使用。

试试这个:

public List<int> TestGetMethod()  
{
return GetIdList().Result;
}

关于c# - 无法从 Task<> 隐式转换类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45077116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com