修改字典中的结构变量 [英] Modify Struct variable in a Dictionary

查看:22
本文介绍了修改字典中的结构变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的结构:

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

但是当我用 foreach 循环遍历它以更改动画帧时,我无法做到...

But when I loop over it with foreach to change animation frame I can't do it...

代码如下:

foreach (KeyValuePair<string, MapTile> tile in tilesData)
{
        if (tilesData[tile.Key].bgFrame >= tilesData[tile.Key].bgAnimation)
        {
            tilesData[tile.Key].bgFrame = 0;
        }
        else
        {
            tilesData[tile.Key].bgFrame++;
        }
}

它给了我编译错误:

Error 1 Cannot modify the return value of 'System.Collections.Generic.Dictionary<string,Warudo.MapTile>.this[string]' because it is not a variable
Error 2 Cannot modify the return value of 'System.Collections.Generic.Dictionary<string,Warudo.MapTile>.this[string]' because it is not a variable

为什么我不能更改字典中结构体中的值?

Why can't I change a value inside a struct which is inside a dictionary?

推荐答案

索引器将返回值的副本.对该副本进行更改不会对字典中的值产生任何影响……编译器正在阻止您编写有问题的代码.如果你想修改字典中的值,你需要使用类似的东西:

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<string, MapTile> 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;
}

这篇关于修改字典中的结构变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆