相关疑难解决方法(0)

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

我试图在.NET 4.5中掌握异步方法语法.我以为我已经明白了究竟例子然而无论异步方法的类型是什么(即Task<T>),我总是得到相同类型的错误错误的转换回T-我明白这是相当多的自动.以下代码生成错误:

无法隐式将类型' System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' 转换为' 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public List<int> TestGetMethod()
{
    return (List<int>)GetIdList();  // compiler error on this line
}
Run Code Online (Sandbox Code Playgroud)

有点可以预见会导致此错误:

无法将类型' System.Threading.Tasks.Task<System.Collections.Generic.List<int>>' 转换为' System.Collections.Generic.List<int>'

任何帮助非常感谢.

c# async-await

63
推荐指数
3
解决办法
9万
查看次数

是否可以将 Task&lt;List&lt;&gt;&gt; 转换为 List&lt;&gt;?

我的一些代码有问题,特别是这部分。我正在调用一个async返回 a的方法Task<List<>>(无法返回常规列表,因为该方法是异步的)。但是,我无法将其转换为常规列表,这正是我所需要的。这甚至可能吗?如果是这样,有人可以帮忙吗?:)

static void Main(string[] args) {
    Program p = new Program();

    List<Product> products = p.getProducts();
}

public async Task<List<Product>> getProducts() {
    // calling woocommerce api
    MyRestApi rest = new MyRestApi("http://someurl.com/wp-json/wc/v2", "consumer key", "consumer secret");
    WCObject wc = new WCObject(rest);

    List<Product> products = await wc.Product.GetAll();

    return await Task.Run(() => new List<Product>(products));
}
Run Code Online (Sandbox Code Playgroud)

c# api asynchronous list woocommerce

6
推荐指数
0
解决办法
1万
查看次数

标签 统计

c# ×2

api ×1

async-await ×1

asynchronous ×1

list ×1

woocommerce ×1