尝试修改项目的值时遇到问题,因为它只是一个只读字段。
KeyValuePair<Tkey, Tvalue>
我尝试了不同的替代方法,例如:
Dictionary<Tkey, Tvalue>
但是我有同样的问题。有没有一种方法可以将值字段设置为新值?
尝试修改项目的值时遇到问题,因为它只是一个只读字段。
KeyValuePair<Tkey, Tvalue>
我尝试了不同的替代方法,例如:
Dictionary<Tkey, Tvalue>
但是我有同样的问题。有没有一种方法可以将值字段设置为新值?
Answers:
您无法修改它,可以将其替换为新的。
var newEntry = new KeyValuePair<Tkey, Tvalue>(oldEntry.Key, newValue);
或字典:
dictionary[oldEntry.Key] = newValue;
KeyValuePair是不可变的,
namespace System.Collections.Generic
{
[Serializable]
public struct KeyValuePair<TKey, TValue>
{
public KeyValuePair(TKey key, TValue value);
public TKey Key { get; }
public TValue Value { get; }
public override string ToString();
}
}
如果您要更新KeyValuePair中的任何现有值,则可以尝试删除现有值,然后添加修改后的值
例如:
var list = new List<KeyValuePair<string, int>>();
list.Add(new KeyValuePair<string, int>("Cat", 1));
list.Add(new KeyValuePair<string, int>("Dog", 2));
list.Add(new KeyValuePair<string, int>("Rabbit", 4));
int removalStatus = list.RemoveAll(x => x.Key == "Rabbit");
if (removalStatus == 1)
{
list.Add(new KeyValuePair<string, int>("Rabbit", 5));
}
的KeyValuePair<TKey, TValue>是C#中的结构和结构是值类型和所提为不可变的。原因很明显,Dictionary<TKey,TValue>应该是一个高性能的数据结构。使用引用类型而不是值类型会占用过多的内存开销。与字典中直接存储的值类型不同,此外,还将为字典中的每个条目分配32位或64位引用。这些引用将指向条目实例的堆。总体性能将迅速下降。
Microsoft选择Dictionary<TKey,TValue>符合结构的结构的规则如下:
如果类型的实例很小且通常是短寿命的或通常嵌入在其他对象中,则考虑定义结构而不是类。
VO避免定义结构,除非类型具有以下所有特征:
Dictionary<long, int> _rowItems = new Dictionary<long, int>();
_rowItems.Where(x => x.Value > 1).ToList().ForEach(x => { _rowItems[x.Key] = x.Value - 1; });
对于字典,我们可以根据某些条件以这种方式更新值。