相关疑难解决方法(0)

为什么可变结构"邪恶"?

在这里讨论了SO之后,我已经多次读过可变结构是"邪恶"的评论(就像这个问题的答案一样).

C#中可变性和结构的实际问题是什么?

c# struct mutable immutability

470
推荐指数
15
解决办法
7万
查看次数

在Dictionary中修改Struct变量

我有这样的结构:

public struct MapTile
{
    public int bgAnimation;
    public int bgFrame;
}
Run Code Online (Sandbox Code Playgroud)

但当我用foreach循环它以改变动画帧我不能这样做...

这是代码:

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++;
        }
}
Run Code Online (Sandbox Code Playgroud)

它给了我编译恐怖:

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
Run Code Online (Sandbox Code Playgroud)

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

c# foreach struct dictionary

33
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

struct ×2

dictionary ×1

foreach ×1

immutability ×1

mutable ×1