修改结构变量在解释 [英] Modify Struct variable in a Dictionary

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

问题描述

我有一个这样的结构:

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...

这里的code:

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++;
        }
}

这让我编译arror:

It gives me compile arror:

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?

推荐答案

索引器将返回的复制的价值。在更改该副本将不会做任何字典中的价值......编译器会从写作马车code阻止你。如果你想要做的修改在字典中的价值,你需要使用这样的:

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;
}

请注意,这是的避免做多次查找没有很好的理由,它原来的code在做什么。

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天全站免登陆