C# 如何重置字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1978821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:21:40  来源:igfitidea点击:

How to reset a Dictionary

c#dictionary

提问by Nano HE

If I declared a dictionary like this:

如果我声明了这样的字典:

private static Dictionary<string, object> aDict = new Dictionary<string, object>();

And now I want to use it at another place. How do I reset it?

现在我想在另一个地方使用它。如何重置?

aDict = new Dictionary<string, object>(); // like this?

aDict = null; // or like this?

or other reset styles?

或其他重置样式?

采纳答案by CMS

You can simply use the Clearmethod, it will remove all keys and values, then you can reuse it without having to create new instances:

您可以简单地使用Clear方法,它将删除所有键和值,然后您可以重用它而无需创建新实例:

aDict.Clear();

回答by Anuraj

Try this

尝试这个

aDict.Clear();

回答by Alan

aDict.Clear();will work.

aDict.Clear();将工作。

回答by manubaum

aDict.Clear();is the only way to go since you don't want to change the reference and keep the same object available at another place

aDict.Clear();是唯一的方法,因为您不想更改引用并在另一个地方保持相同的对象可用

回答by Tore Aurstad

Running a decompile of the Clear method in Resharper on a Dictionary object shows this:

在 Resharper 中对 Dictionary 对象运行 Clear 方法的反编译显示:

/// <summary>Removes all keys and values from the <see cref="T:System.Collections.Generic.Dictionary`2" />.</summary>
[__DynamicallyInvokable]
public void Clear()
{
  if (this.count <= 0)
    return;
  for (int index = 0; index < this.buckets.Length; ++index)
    this.buckets[index] = -1;
  Array.Clear((Array) this.entries, 0, this.count);
  this.freeList = -1;
  this.count = 0;
  this.freeCount = 0;
  ++this.version;
}

The dictionary contains an integer array of buckets and other control variables that are either set to -1 or 0 to effectively clear the keys and values from the dictionary object. It is pretty many variables representing a valid state of the Dictionary as we can see in the .NET source code. Interesting.

字典包含桶和其他控制变量的整数数组,这些变量设置为 -1 或 0 以有效清除字典对象中的键和值。正如我们在 .NET 源代码中看到的那样,它有很多变量代表字典的有效状态。有趣的。

回答by frmbelz

Good to call Count before calling Clear if Dictionary might be empty

如果字典可能为空,则在调用 Clear 之前先调用 Count

if (aDict.Count > 0)
{
    aDict.Clear();
}

Count is supposedly faster than Clear so you avoid running Clear on zero elements Dictionary.

Count 据说比 Clear 快,因此您可以避免在零元素 Dictionary 上运行 Clear。