属性KeyValuePair <TKey,Tvalue> .Value没有setter

cho*_*ppy 7 .net c# keyvaluepair

我用a Dictionary<int, KeyValuePair<bool, int>>来保存数据.

不时,我需要递增intKeyValuePair,但它不会让我,因为它没有制定者.有没有办法增加它?

代码示例:

Dictionary<int, KeyValuePair<bool, int>> mDictionary = 
    new Dictionary<int, KeyValuePair<bool, int>>();

mDictionary[trapType].Value++;
//Error: The property KeyValuePair<TKey, Tvalue>>.Value has no setter
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 22

有没有办法增加它?

No. KeyValuePair是不可变的 - 它也是一个值类型,因此在创建副本后更改Value属性的值无论如何都无济于事.

你必须写这样的东西:

var existingValue = mDictionary[trapType];
var newValue = new KeyValuePair<bool, int>(existingValue.Key,
                                           existingValue.Value + 1);
mDictionary[trapType] = newValue;
Run Code Online (Sandbox Code Playgroud)

虽然它很丑陋 - 你真的需要价值KeyValuePair吗?

  • 我建议`Tuple`.创建一个的最短方法是`Tuple.Create(existingValue.Key,existingValue.Value + 1)`.虽然创建一个类(如果是逻辑的)会更好地避免不必要的`new()`. (3认同)