WPF新手开发API应用报错:无法隐式转换Task<List<CoinModel>>到IEnumerable
问题分析与解决方法
错误根源
你直接将GetCoinInfo的返回值(Task<List<CoinModel>>)赋值给lBox.ItemsSource,但ItemsSource需要的是IEnumerable类型的实际数据,而非异步任务对象。GetCoinInfo是异步方法,调用时必须通过await关键字获取任务执行完成后的实际结果。
修复步骤
1. 将按钮点击事件改为异步方法
WPF事件处理程序允许使用async void(仅适用于事件处理场景),这样就能在方法内等待异步操作完成:
private async void Button_Click(object sender, RoutedEventArgs e) { string txtBoxValue = txtCoins.Text; var coinList = await GetCoinInfo(txtBoxValue); lBox.ItemsSource = coinList; }
2. 匹配API返回的数据格式
如果传入单个ID时,API返回的是单个CoinModel对象而非列表,那么ReadAsAsync<List<CoinModel>>会触发反序列化错误。此时需要调整代码,将单个对象包装成列表返回:
public async Task<List<CoinModel>> GetCoinInfo(string coinId) { ApiHelper.InitializeClient(); try { var response = await ApiHelper.Client.GetAsync($"{coinId}"); response.EnsureSuccessStatusCode(); // 若API返回单个对象,改用此反序列化方式 var singleCoin = await response.Content.ReadAsAsync<CoinModel>(); return new List<CoinModel> { singleCoin }; } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } }
3. 修正CoinModel的PriceUsd类型
PriceUsd定义为int不合理,加密货币价格通常是带小数的数值,用int会导致解析失败或精度丢失,建议改为decimal(更适合货币类型):
public class CoinModel { public string Id { get; set; } public string Symbol { get; set; } public string Name { get; set; } public string Rank { get; set; } public string MarketCapUsd { get; set; } public string VolumeUsd24Hr { get; set; } public decimal PriceUsd { get; set; } public string ChangePercent24Hr { get; set; } }
内容的提问来源于stack exchange,提问作者Curious User
相关产品推荐
相关产品推荐

