c# - wherelistiterator - No se puede convertir implícitamente el tipo de Tarea<>
no se puede convertir un objeto de tipo wherelistiterator (3)
Dependiendo de lo que intente hacer, puede bloquear con GetIdList (). Resultado (generalmente una mala idea, pero es difícil decir el contexto) o usar un marco de prueba que admita métodos de prueba asíncronos y hacer que el método de prueba lo haga var results = aguardar GetIdList ();
Estoy intentando dominar la sintaxis del método async en .NET 4.5. Pensé que había entendido los ejemplos exactamente; sin embargo, independientemente del tipo de método asíncrono (es decir, Task<T> ), siempre obtengo el mismo tipo de error de error en la conversión de nuevo a T , que entendí que era prácticamente automático. . El siguiente código produce el error:
No se puede convertir implícitamente el tipo ''
System.Threading.Tasks.Task<System.Collections.Generic.List<int>>'' a ''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;
}
}
Falla si explícitamente lanzo el resultado también. Esta:
public List<int> TestGetMethod()
{
return (List<int>)GetIdList(); // compiler error on this line
}
de manera algo predecible resulta en este error:
No se puede convertir el tipo ''
System.Threading.Tasks.Task<System.Collections.Generic.List<int>>'' a ''System.Collections.Generic.List<int>''
Cualquier ayuda muy apreciada.
El principal problema con su ejemplo es que no puede convertir implícitamente los tipos de devolución de Task<T> tipo base T Necesita usar la propiedad Task.Result. Tenga en cuenta que Task.Result bloqueará el código asincrónico y se debe usar con cuidado.
Pruebe esto en su lugar:
public List<int> TestGetMethod()
{
return GetIdList().Result;
}
También necesita hacer TestGetMethod async y attach GetIdList(); delante de GetIdList(); desenvolverá la tarea a List<int> , por lo tanto, si su función auxiliar está regresando a la tarea, asegúrese de haber aguardado mientras llama también a la función async .
public Task<List<int>> TestGetMethod()
{
return GetIdList();
}
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;
}
}
Otra opción
public async void TestGetMethod(List<int> results)
{
results = await GetIdList(); // await will unwrap the List<int>
}