c# modifying structs in a List

后端 未结 5 800
天涯浪人
天涯浪人 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:29

    Looking at the for-loop approach, the reason (and solution) for this is given in the documentation for the compilation error:

    An attempt was made to modify a value type that is produced as the result of an intermediate expression but is not stored in a variable. This error can occur when you attempt to directly modify a struct in a generic collection.

    To modify the struct, first assign it to a local variable, modify the variable, then assign the variable back to the item in the collection.

    So, in your for-loop, change the following lines:

    catSlots[s].subItems.Clear();
    catSlots[s].subItems = sortedSubTemp;   // ERROR: see below
    

    ...into:

    slotInfo tempSlot = gAllCats[0].items[s];
    tempSlot.subItems  = sortedSubTemp;
    gAllCats[0].items[s] = tempSlot;
    

    I removed the call to the Clear method, since I don't think it adds anything.

提交回复
热议问题