Dictionary中的键是?不可变的?
我从 API 返回一个 Dictionary
,但根据某些规则需要修改一些键名称。
在开始复制到新的 Dictionary
之前,我只想确认 Dictionary
中的键是不可变的。
I get a Dictionary<string, string>
back from an API but depending on certain rules need to modify some of the key names.
Before I head down the road of copying to a new Dictionary
I just wanted to confirm that the keys in a Dictionary<TKey, TValue>
are immutable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你是对的,如果密钥发生变化,您将需要删除旧密钥的条目并插入新密钥的新条目。
如果只有部分键发生变化,则无需复制整个字典。
Dictionary
上的添加和删除操作大致都是 O(1) 操作。You are right, if the key changes, you will need to remove the entry with the old key and insert a new entry with the new key.
If only some of the keys change, you don't need to copy the entire dictionary. Both Add and Remove operations on
Dictionary
are roughly O(1) operations.更像是您必须确保您用于
TKey
的类型(如果它是引用类型)是不可变的。顺便说一句,字符串是不可变的。值类型可以是可变的,但您没有机会修改字典
中存储的键。It is more like that you have to make sure that the type you use for
TKey
is immutable if it is a reference type. String is immutable, by the way. Value types can be mutable, but you don't get the opportunity to modify the stored key in theDictionary
.字典中的键是不可变的。
例如,以下代码:
将抛出以下编译器错误:
如此,Dictionary如果您使用引用类型,可能具有可变键,请参阅:
C# Dictionary< ;>和可变键
(我知道,我知道,字符串是引用类型......但上面的链接将解释......)
The keys in a Dictionary<string, string> are immutable.
For instance, the following code:
Will throw the following compiler error:
That being said, a Dictionary<T, T> may have mutable keys if you use a reference type, see:
C# Dictionary<> and mutable keys
(I know, I know, strings are reference types... but the link above will explain...)