I got a problem when I try to modify the value of an item because its only a read only field.
当我尝试修改项目的值时,我遇到了一个问题,因为它只是一个只读字段。
KeyValuePair<Tkey, Tvalue>
I've tried different alternatives like:
我尝试了不同的替代方案,如:
Dictionary<Tkey, Tvalue>
but there I have the same problem. Is there a way to set the value field to an new value?
但我有同样的问题。有没有办法将值字段设置为新值?
3 个解决方案
#1
79
You can't modify it, you can replace it with a new one.
您无法修改它,您可以用新的替换它。
var newEntry = new KeyValuePair<Tkey, Tvalue>(oldEntry.Key, newValue);
or for dictionary:
或者字典:
dictionary[oldEntry.Key] = newValue;
#2
8
KeyValuePair<TKey, TValue>
is immutable. You need to create a new one with the modifified key or value. What you actually do next depends on your scenario, and what exactly you want to do...
KeyValuePair
#3
8
Here, if you want to make KeyValuePair mutable.
在这里,如果你想让KeyValuePair变得可变。
Make a custom class.
制作自定义课程。
public class KeyVal<Key, Val>
{
public Key Id { get; set; }
public Val Text { get; set; }
public KeyVal() { }
public KeyVal(Key key, Val val)
{
this.Id = key;
this.Text = val;
}
}
so we can make it use in wherever in KeyValuePair.
所以我们可以在KeyValuePair的任何地方使用它。
#1
79
You can't modify it, you can replace it with a new one.
您无法修改它,您可以用新的替换它。
var newEntry = new KeyValuePair<Tkey, Tvalue>(oldEntry.Key, newValue);
or for dictionary:
或者字典:
dictionary[oldEntry.Key] = newValue;
#2
8
KeyValuePair<TKey, TValue>
is immutable. You need to create a new one with the modifified key or value. What you actually do next depends on your scenario, and what exactly you want to do...
KeyValuePair
#3
8
Here, if you want to make KeyValuePair mutable.
在这里,如果你想让KeyValuePair变得可变。
Make a custom class.
制作自定义课程。
public class KeyVal<Key, Val>
{
public Key Id { get; set; }
public Val Text { get; set; }
public KeyVal() { }
public KeyVal(Key key, Val val)
{
this.Id = key;
this.Text = val;
}
}
so we can make it use in wherever in KeyValuePair.
所以我们可以在KeyValuePair的任何地方使用它。