是否可以做类似的事情: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;
如果您想更改其中一个值,请不要使用元组 - 使用可变类。否则,您执行此操作的方式是合适的(保留第二个值)。
EDIT -
感谢 Theodor Zoulias 指出我的推理有缺陷。元组是可变的,但由于某种原因(我不确定为什么),您无法使用字典访问器更改内联元组的属性。当您尝试对返回值使用变异运算符时(例如dictTupleTest[key]++
),但我不明白为什么要调用属性set
不应该被允许。
无论如何,将结果分配给变量does work:
dictTupleTest.Add(key, (true, false));
var x = dictTupleTest[key];
x.Item1 = false;
Console.WriteLine(dictTupleTest[key]); // outputs (false, false)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)