c# modifying structs in a List

后端 未结 5 795
天涯浪人
天涯浪人 2021-01-01 19:57

Short question: How can I modify individual items in a List? (or more precisely, members of a struct stored in a List?)

Full e

5条回答
  •  温柔的废话
    2021-01-01 20:13

    The foreach loop doesn't work because sInf is a copy of the struct inside items. Changing sInf will not change the "actual" struct in the list.

    Clear works because you aren't changing sInf, you are changing the list inside sInf, and Ilist will always be a reference type.

    The same thing happens when you use the indexing operator on IList - it returns a copy instead of the actual struct. If the compiler did allow catSlots[s].subItems = sortedSubTemp;, you'll be modifying the subItems of the copy, not the actual struct. Now you see why the compiler says the return value is not a variable - the copy cannot be referenced again.

    There is a rather simple fix - operate on the copy, and then overwrite the original struct with your copy.

    for (int s = 0; s < gAllCats[c].items.Count; s++)
    {
                var sortedSubItems =
                                from itemInfo iInf in gAllCats[c].items[s].subItems
                                orderby iInf.subNum ascending
                                select iInf;
                IList sortedSubTemp = new List();
                foreach (itemInfo iInf in sortedSubItems)
                {
                                sortedSubTemp.Add(iInf);
                }
                var temp = catSlots[s];
                temp.subItems = sortedSubTemp;
                catSlots[s] = temp;
    }
    

    Yes, this results in two copy operations, but that's the price you pay for value semantics.

提交回复
热议问题