如何销毁 C# 数据,例如 Dictionary<string, List<Action<object>>>?

Jer*_*Lee 1 c# delegates dictionary

我定义了一个对象Dictionary<string, List<Action<object>>>来存储一些要调用的委托方法。如果我想毁掉这本词典。我需要List.Clear()先在字典中调用吗?还是直接打电话Dictionary.Clear就可以了?

这个:

foreach(KeyValuePair<string, List<Action<object>>> kvp in dict)
{
   kvp.Value.Clear();
}

dict.Clear();
dict = null;
Run Code Online (Sandbox Code Playgroud)

或者这个:

dict.Clear();
dict = null;
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

如果您要删除对 的最后一个实时引用dict,请不要理会其中的任何一个:null如果仍在范围内,则只需进行分配,或者如果 的范围即将结束,dict则不执行任何操作。dict

不需要显式清除字典或它包含的任何列表,因为垃圾收集器会以任何一种方式处理它。显式清除字典及其包含的列表会浪费 CPU 周期。