【问题标题】:Setting dictionary tuple values directly直接设置字典元组值
【发布时间】:2021-08-02 05:06:03
【问题描述】:

在以下情况下是否可以做类似的事情: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&lt;int, (bool, bool)&gt;.this[int]' because it is not a variable.

或者有更好的方法吗?

【问题讨论】:

  • Built-in Tuples 是不可变的。一旦创建,它们就是只读的。因此,您需要更改整个设置。
  • 使用类对象代替元组并定义你的属性。

标签: c# dictionary tuples


【解决方案1】:

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

var x = dictTupleTest[key];
x.Item1 = toggle;

如果您想更改其中一个值,请不要使用元组 - 使用可变类。否则,您的做法是合适的(保留第二个值)。

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多