我看到了一些关于这个问题的问题,并进行了一些研究。
据我了解,当您在IEnumerable上运行foreach时:如果T是引用类型(例如类),则应该能够在循环内部修改对象的属性。 如果T是值类型(例如结构体),则不起作用,因为迭代变量将是局部副本。
我正在使用以下代码开发Windows Store应用程序:
我的类:
public class WebResult
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string DisplayUrl { get; set; }
public string Url { get; set; }
public string TileColor
{
get
{
string[] colorArray = { "FFA200FF", "FFFF0097", "FF00ABA9", "FF8CBF26",
"FFA05000", "FFE671B8", "FFF09609", "FF1BA1E2", "FFE51400", "FF339933" };
Random random = new Random();
int num = random.Next(0, (colorArray.Length - 1));
return "#" + colorArray[num];
}
}
public string Keywords { get; set; }
}
代码如下:
IEnumerable<WebResult> results = from r in doc.Descendants(xmlnsm + "properties")
select new WebResult
{
Id = r.Element(xmlns + "ID").Value,
Title = r.Element(xmlns + "Title").Value,
Description = r.Element(xmlns +
"Description").Value,
DisplayUrl = r.Element(xmlns +
"DisplayUrl").Value,
Url = r.Element(xmlns + "Url").Value,
Keywords = "Setting the keywords here"
};
foreach (WebResult result in results)
{
result.Keywords = "These, are, my, keywords";
}
if (control is GridView)
{
(control as GridView).ItemsSource = results;
}
一旦结果显示,"Keywords"属性就是"在此设置关键字"。如果我在foreach循环中放置断点,我可以看到结果对象没有被修改...有什么想法吗?我是不是错过了一些明显的东西?IEnumerable在.NET For Windows Store Apps中的行为是否不同?