c# - 直接设置字典元组值
问题描述
是否可以做类似的事情:dictTupleTest[key].Item1 = toggle;
在以下情况下?
Dictionary<int, (bool, bool)> dictTupleTest = new Dictionary<int, (bool, bool)>();
var key = 3;
var toggle = false;
dictTupleTest.Add(key, (true, false));
//This works
dictTupleTest[key] = (toggle, dictTupleTest[key].Item2);
//While this gives an error
dictTupleTest[key].Item1 = toggle;
错误:Error CS1612: Cannot modify the return value of 'Dictionary<int, (bool, bool)>.this[int]' because it is not a variable.
或者有更好的方法吗?
解决方案
元组是不可变的;它存储在字典中的事实是无关紧要的。你会得到同样的错误:
var x = dictTupleTest[key];
x.Item1 = toggle;
如果要更改其中一个值,请不要使用元组 - 使用可变类。否则,您的操作方式是合适的(保留第二个值)。
编辑 -
感谢 Theodor Zoulias 指出我的推理有缺陷。元组是可变的,但由于某种原因(我不确定为什么),您不能使用字典访问器更改内联元组的属性。当您尝试在返回值(如 )上使用变异运算符时,该错误更为常见 dictTupleTest[key]++
,但我不明白为什么set
不允许调用属性。
无论如何,将结果分配给变量确实有效:
dictTupleTest.Add(key, (true, false));
var x = dictTupleTest[key];
x.Item1 = false;
Console.WriteLine(dictTupleTest[key]); // outputs (false, false)
推荐阅读
- asp.net - 点击时超链接没有反应
- flask - 如何使用 sqlalchemy 将 gunicorn 烧瓶容器与 Maria DB 容器连接起来?
- django - 如何在model.py中声明查询集
- python - 如何在 Python 中使用正则表达式替换缩写中的点?
- bash - 将 grep 与 for 循环一起使用时不必要的换行符
- javascript - 如何从箭头函数提醒多个回调结果?
- reactjs - 组件渲染后更新本地状态
- php - beginSignedUploadSession() 在 PHP AppEngine Flex 上导致错误,但不是在本地
- c# - 在使用 wpf 实时图表库时,我无法从数据中显示折线图。我怀疑数据绑定错误
- wpf - WPF 如何将动态创建的复选框绑定到 LiveCharts 中动态创建的系列?