我正在使用以下代码:
private string covertRss(string url)
{
var s = RssReader.Read(url);
StringBuilder sb = new StringBuilder();
foreach (RssNews rs in s) //ERROR LINE
{
sb.AppendLine(rs.Title);
sb.AppendLine(rs.PublicationDate);
sb.AppendLine(rs.Description);
}
return sb.ToString();
}
我收到一个错误:
Error 1 foreach statement cannot operate on variables of type 'System.Threading.Tasks.Task(System.Collections.Generic.List(Cricket.MainPage.RssNews))' because 'System.Threading.Tasks.Task(System.Collections.Generic.List(Cricket.MainPage.RssNews))' does not contain a public definition for 'GetEnumerator'
RssNews 类是:
public class RssNews
{
public string Title;
public string PublicationDate;
public string Description;
}
我应该添加什么代码才能消除错误并且不影响代码的用途? 提前致谢!
RssReader.Read() 代码
public class RssReader
{
public static async System.Threading.Tasks.Task<List<RssNews>> Read(string url)
{
HttpClient httpClient = new HttpClient();
string result = await httpClient.GetStringAsync(url);
XDocument document = XDocument.Parse(result);
return (from descendant in document.Descendants("item")
select new RssNews()
{
Description = descendant.Element("description").Value,
Title = descendant.Element("title").Value,
PublicationDate = descendant.Element("pubDate").Value
}).ToList();
}
}
最佳答案
你需要使用await
:
foreach (RssNews rs in await s)
或:
var s = await RssReader.Read(url);
不使用Result
;如果你这样做,你可以很容易地 cause a deadlock我在我的博客上描述的。
作为旁注,我建议您阅读并遵循 Task-based Asynchronous Pattern documentation 中的指南。 .如果这样做,您会发现您的方法 Read
应该命名为 ReadAsync
,这会强烈提示您的调用代码需要使用 await
:
var s = await RssReader.ReadAsync(url);
关于c# - foreach 语句给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19733581/