public async Task<ObservableCollection<T>> All(string url)
{
ObservableCollection<T> Collection=new ObservableCollection<T>();
try
{
var response = await httpclient.GetResponseAsync(url);
if(!string.IsNullOrEmpty(response))
{
var content = JsonConvert.DeserializeObject<T>(response);
foreach(var item in content)
{
Collection.Add(item);
}
}
else
{
throw new Exception();
}
}
catch (HttpRequestException )
{
}
catch(TaskCanceledException )
{
}
catch(Exception)
{
}
//throw new NotImplementedException();
return Collection;
}
如何将内容逐个循环到Collection作为我的代码。
Ex:ObservableCollection **&#34;&lt;行动&gt;&#34; ** getListAll = t.All(&#34; .....&#34;);
CS1579 foreach语句不能对类型&#39; T&#39;的变量进行操作。因为&#39; T&#39;不包含&#39; GetEnumerator&#39;的公开定义
答案 0 :(得分:1)
首先这个方法不会编译你必须在方法之后添加(全部)。其次,如果您确定响应将是T的集合,您必须反序列化为IEnumerable,那么您将能够使用foreach。
public async Task<ObservableCollection<T>> All(string url)
{
ObservableCollection<T> Collection=new ObservableCollection<T>();
try
{
var response = await httpclient.GetResponseAsync(url);
if(!string.IsNullOrEmpty(response))
{
var content = JsonConvert.DeserializeObject<IEnumerable<T>>(response);
foreach(var item in content)
{
Collection.Add(item);
}
}
else
{
throw new Exception();
}
}
catch (HttpRequestException )
{
}
catch(TaskCanceledException )
{
}
catch(Exception)
{
}
//throw new NotImplementedException();
return Collection;
}
答案 1 :(得分:0)
要进行编译,只需将方法签名更改为:
struct User {
var firstName: String?
var lastName: String?
}
var allThePeople = [User(firstName: "John", lastName: "Doe"), User(firstName: "Jane", lastName: "Doe"), User(firstName: "John", lastName: "Travolta")];
我怀疑你也没有正确序列化,但没有底层代码就无法确定。考虑使用包装类或查看The documentation。