【问题标题】:Specified cast is not valid in Xamarin Forms指定的强制转换在 Xamarin 表单中无效
【发布时间】:2022-01-13 03:40:18
【问题描述】:

有谁知道当出现像 Specified cast is not valid 这样的错误时会发生什么?我评论了错误发生的那一行

private async void GetEmployee()
 {
     var _token = await GetAccessToken();            
     using (var _client = new HttpClient())
     {
         var _uri = "domain here";

         _client.BaseAddress = new Uri(_uri);
         _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);

         var _response = await _client.GetAsync("endpoint here'");

         var Emp = JsonConvert.DeserializeObject<Employee>(await _response.Content.ReadAsStringAsync());
         Employee = new ObservableCollection<Employee>((IEnumerable<Employee>)Emp); //Im having error on this line
     }
 }

 ObservableCollection<Employee> _employee;
 public ObservableCollection<Employee> Employee
 {
     get
     {
         return _employee;
     }
     set
     {
         _employee = value;
         OnPropertyChanged();
     }
 }

【问题讨论】:

  • 为什么允许将单个元素转换为该元素的数组?尝试将new[] { Emp } 传递给new ObservableCollection&lt;Employee&gt; 构造函数调用,而不是传递Emp
  • 嗨@UweKeim 我是新手,我该怎么办?

标签: c# xamarin xamarin.forms


【解决方案1】:

如何改变这个:

Employee = new ObservableCollection<Employee>((IEnumerable<Employee>)Emp);

到这里:

Employee = new ObservableCollection<Employee>(new[] {Emp});

See .NET Fiddle example.

See ObservableCollection documentation.


new[] { ... }new Employee[] { ... } 的缩写,并使用{} 中的初始值创建一个新数组。

See array documentation.

【讨论】:

  • 嗨@UweKeim 我试过了,它工作我是编程新手谢谢你帮助我:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 2019-03-27
  • 1970-01-01
  • 2018-05-27
  • 2014-07-30
  • 2012-06-12
相关资源
最近更新 更多