首页 > 解决方案 > 直接设置字典元组值

问题描述

是否可以做类似的事情: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.

或者有更好的方法吗?

标签: c#dictionarytuplesvalue-type

解决方案


元组是不可变的;它存储在字典中的事实是无关紧要的。你会得到同样的错误:

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)

推荐阅读