Modify Struct variable in a Dictionary

前端 未结 4 729
孤独总比滥情好
孤独总比滥情好 2020-11-27 19:51

I have a struct like this:

public struct MapTile
{
    public int bgAnimation;
    public int bgFrame;
}

But when I loop over it with forea

4条回答
  •  鱼传尺愫
    2020-11-27 20:29

    The indexer will return a copy of the value. Making a change to that copy won't do anything to the value within the dictionary... the compiler is stopping you from writing buggy code. If you want to do modify the value in the dictionary, you'll need to use something like:

    // Note: copying the contents to start with as you can't modify a collection
    // while iterating over it
    foreach (KeyValuePair pair in tilesData.ToList())
    {
        MapTile tile = pair.Value;
        tile.bgFrame = tile.bgFrame >= tile.bgAnimation ? 0 : tile.bgFrame + 1;
        tilesData[pair.Key] = tile;
    }
    

    Note that this is also avoiding doing multiple lookups for no good reason, which your original code was doing.

    Personally I'd strongly advise against having a mutable struct to start with, mind you...

    Of course, another alternative is to make it a reference type, at which point you could use:

    // If MapTile is a reference type...
    // No need to copy anything this time; we're not changing the value in the
    // dictionary, which is just a reference. Also, we don't care about the
    // key this time.
    foreach (MapTile tile in tilesData.Values)
    {
        tile.bgFrame = tile.bgFrame >= tile.bgAnimation ? 0 : tile.bgFrame + 1;
    }
    

提交回复
热议问题