【问题标题】:ForEach loop not changing property of classForEach 循环不改变类的属性
【发布时间】: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 中的行为是否有所不同?

【问题讨论】:

标签: c# foreach windows-store-apps ienumerator


【解决方案1】:

这被称为deferred executionresults 是每次迭代时都会执行的查询。在您的情况下,它被评估了两次,一次在 for 循环中,第二次在数据绑定时。

您可以通过执行以下操作来验证这一点

var results2 = results.ToList();

foreach (WebResult result in results2)
{
    result.Keywords = "These, are, my, keywords";
}

if (control is GridView)
{
    (control as GridView).ItemsSource = results2;
}

您应该会看到您的更改仍然存在。

【讨论】:

  • 多次迭代是否是结果未被修改或类型 IEnumerable 的原因
  • 谢谢,我从可能的重复链接中得到它。这是由于多次迭代。
  • @Sundeep 这不是多次迭代,因为您可能误解了 IEnumerable 的语义。很多人第一次犯这个错误。
  • 是的,我认为 IEnumerable 只是充当迭代器,但不知道它每次都运行在新实例上。
  • @Sundeep Slacks 对这个问题给出了比我在这里做的更好的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 2021-01-25
相关资源
最近更新 更多