我如何确定 C# 字典的当前容量?

How can i determine a C# Dictionary's current capacity?

List 具有用于获取 Count and its Capacity. Dictionaries, like all collections, have the Count property too, and it has a capacity because it has several constructors that allow you to specify it and the documentation for the Add 方法提及它的单独属性。但是,我看不到任何查询字典当前容量的方法。

即使无法获得字典的当前容量,是否有任何方法可以预测何时可能发生重新分配?

字典的工作方式与列表不同。如果您检查 Microsoft 提供的 source code。您可以找到多个可能有用的私有字段。

请注意,这是一个封装的实现细节,您不应在生产代码中依赖它作为名称,私有成员和内部成员的行为可能会更改,恕不另行通知!

您有内部数组 int[] bucketsEntry[] entries。您还有 int freeListint freeCount。您可以使用反射来解决这些问题。

为了回答您的问题,是的,每次插入都会触发重新分配,这是实际代码:

int index;
if (freeCount > 0)
{
    index = freeList;
    freeList = entries[index].next;
    freeCount--;
}
else
{
    if (count == entries.Length)
    {
        Resize();
        targetBucket = hashCode % buckets.Length;
    }
    index = count;
    count++;
}