【问题标题】:How do I debug "cannot convert to system.collections.generic.list" error如何调试“无法转换为 system.collections.generic.list”错误
【发布时间】:2020-03-13 14:26:55
【问题描述】:
var httpClient = new HttpClient();
        var response = await httpClient.GetStringAsync("http://192.168.1.57/smsapi/api/kullanici/" + viewModel.Item.ID);
        var GrupKullanicilarList = JsonConvert.DeserializeObject<Kullanicilarr>(response);
       ---> string TelefonNoList = GetTelno(GrupKullanicilarList);


public string GetTelno(List<Kullanicilarr> GrupKullanicilarList)
    {
        List<string> TelefonNoList = new List<string>();
        foreach (Kullanicilarr Kullanici in GrupKullanicilarList)
        {
            TelefonNoList.Add("<TelefonNo><TelNo>" + Kullanici.Telefonno.ToString() + "</TelNo></TelefonNo>");
        }

        return string.Join("\n", TelefonNoList);

它在我放箭头的开头的第四行给出了一个错误:“无法从'SmsApp.Models.Kullanicilarr'转换为'System.Collections.Generic.List'我应该如何写最后一行?

【问题讨论】:

  • 像这样 --- string TelefonNoList = GetTelno(new List&lt;Kullanicilarr&gt;() {GrupKullanicilarList });。但是想了解 API 返回的是单个对象还是集合?根据您当前的代码,您需要一个对象JsonConvert.DeserializeObject&lt;Kullanicilarr&gt;(response);如果是单则重命名变量名。

标签: c# .net xamarin error-handling


【解决方案1】:

在第 3 行,

 var GrupKullanicilarList = JsonConvert.DeserializeObject<Kullanicilarr>(response);

您正在将 http 响应反序列化为 Kullanicilarr 对象。

并且您将Kullanicilarr 传递给GetTelno(List&lt;Kullanicilarr&gt; GrupKullanicilarList),它需要Kullanicilarr 列表。这就是您收到此错误的原因。

你能检查一下http响应是否返回List&lt;Kullanicilarr&gt;吗? 如果是,那么您需要将第 3 行更改为,

 var GrupKullanicilarList = JsonConvert.DeserializeObject<List<Kullanicilarr>>(response);

如果不是,则需要将方法GetTelno参数更改为 GetTelno(Kullanicilarr GrupKullanicilarList) 并更新其功能,因为您将获得单个对象而不是数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多