gpt4 book ai didi

c# - Dictionary.Clear 和 new Dictionary() 的区别

转载 作者:IT王子 更新时间:2023-10-29 04:13:29 28 4
gpt4 key购买 nike

C# 中 Dictionary.Clearnew Dictionary() 之间的主要区别是什么?在哪些情况下推荐使用哪一种?

最佳答案

Dictionary.Clear() 将删除字典中的所有 KeyValue 对。执行 new Dictionary() 将创建一个新的字典实例。

当且仅当旧版本的字典未被另一个引用作为根时,创建新字典将使整个字典及其内容(未在其他地方作为根)可供 GC 清理。

Dictionary.Clear() 将使 KeyValue 对可用于清理。

在实践中,这两个选项往往会产生非常相似的效果。区别在于在方法中使用 this 时会发生什么:

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

关于c# - Dictionary.Clear 和 new Dictionary() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1400532/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com