簡體   English   中英

ForEach循環不改變類的屬性

[英]ForEach loop not changing property of class

我已經看到了幾個關於這個的問題,並做了一些研究。

我的理解是當你在IEnumerable上運行foreach時:如果T是一個引用類型(例如Class),你應該能夠在循環中修改對象的屬性。 如果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中對Windows Store應用程序的行為有何不同?

這稱為deferred execution ; results是每次迭代時執行的查詢。 在你的情況下,它被評估兩次,一次在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;
}

您應該看到您的更改仍然存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM