Dictionary.clear和新词典之间的差异() [英] Differences between Dictionary.clear and new Dictionary()
问题描述
什么是在C#中的 Dictionary.Clear
和新词典()
的主要区别?哪一个被推荐用于哪些情况?
What are the key differences between Dictionary.Clear
and new Dictionary()
in C#? Which one is recommended for which cases?
推荐答案
Dictionary.Clear()
将删除所有的 KEYVALUE
字典中对。做新词典()
将创建字典的新实例。
Dictionary.Clear()
will remove all of the KeyValue
pairs within the dictionary. Doing new Dictionary()
will create a new instance of the dictionary.
如果,且仅当,老版本的字典的根源并非是由另一个参考,创建一个新的字典将使整个字典,它的内容由GC(这是其他地方没有根),可用于清理。
If, and only if, the old version of the dictionary is not rooted by another reference, creating a new dictionary will make the entire dictionary, and it's contents (which are not rooted elsewhere) available for cleanup by the GC.
Dictionary.Clear()
将提供用于清理的 KEYVALUE
对。
Dictionary.Clear()
will make the KeyValue
pairs available for cleanup.
在实践中,这两个选项将倾向于具有非常相似的效果。差异会时,这是一个方法中使用发生了什么:
In practice, both options will tend to have very similar effects. The difference will be what happens when this is used within a method:
void NewDictionary(Dictionary<string,int> dict)
{
dict = new Dictionary<string,int>(); // Just changes the local reference
}
void ClearDictionary(Dictionary<string,int> dict)
{
dict.Clear();
}
// When you use this...
Dictionary<string,int> myDictionary = ...; // Set up and fill dictionary
NewDictionary(myDictionary);
// myDictionary is unchanged here, since we made a new copy, but didn't change the original instance
ClearDictionary(myDictionary);
// myDictionary is now empty
这篇关于Dictionary.clear和新词典之间的差异()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!