栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

修改字典中的Struct变量

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

修改字典中的Struct变量

索引器将返回该值的 副本
。对该副本进行更改不会对字典中的值产生任何影响……编译器阻止您编写错误的代码。如果要修改字典中的值,则需要使用类似以下内容的方法:

// Note: copying the contents to start with as you can't modify a collection// while iterating over itforeach (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;}

请注意,这 避免了无缘无故地进行多次查找(原始代码正在这样做)。

就个人而言,我强烈建议 不要 从一个可变的结构开始,请注意…

当然,另一种选择是使其成为引用类型,此时您可以使用:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/483975.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号