本文介绍了属性KeyValuePair< TKey,Tvalue> .Value没有设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Dictionary<int, KeyValuePair<bool, int>>来保存数据.

I'm using a Dictionary<int, KeyValuePair<bool, int>> to hold data.

我有时需要在KeyValuePair中增加int,但是它不会让我,因为它没有设置器.有没有办法增加它?

From time to time I need to increment the int in the KeyValuePair, but it won't let me, because it has no setter. Is there a way to increment it?

代码示例:

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

推荐答案

不. KeyValuePair是不可变的-也是值类型,因此在创建副本后更改Value属性的值仍然无济于事.

No. KeyValuePair is immutable - it's also a value type, so changing the value of the Value property after creating a copy wouldn't help anyway.

您必须编写如下内容:

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

虽然很丑-您真的需要将该值设为KeyValuePair吗?

It's pretty ugly though - do you really need the value to be a KeyValuePair?

这篇关于属性KeyValuePair&lt; TKey,Tvalue&gt; .Value没有设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 03:39