【发布时间】:2013-02-01 16:56:18
【问题描述】:
我已经看到了一些关于此的问题,并进行了一些研究。
我的理解是,当您在 IEnumerable 上运行 foreach 时:如果 T 是引用类型(例如类),您应该能够在循环中修改对象的属性。如果 T 是值类型(例如 Struct),这将不起作用,因为迭代变量将是本地副本。
我正在使用以下代码开发 Windows 应用商店应用:
我的班级:
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;
}
一旦显示结果,“关键字”属性就是“在此处设置关键字”。如果我在 foreach 循环中放置一个断点,我可以看到结果对象没有被修改...
关于发生了什么的任何想法?我只是错过了一些明显的东西吗? IEnumerable 在 .NET For Windows Store Apps 中的行为是否有所不同?
【问题讨论】:
-
如果你手头有 Resharper,警告“IEnumerable 的可能多重枚举”可能是一个提示。您正在为每个枚举生成一个新集合。
标签: c# foreach windows-store-apps ienumerator