Dictionary<string, T> 使用的默认 StringComparer

Default StringComparer used by Dictionary<string, T>

我习惯于在创建由 string 键控的 Dictionary 时指定 StringComparer,我想知道如果指定 none 会使用什么比较器。 docs

This constructor uses the default generic equality comparer, EqualityComparer.Default

调试显示 System.Collections.Generic.GenericEqualityComparer<string> 的 运行 时间类型,但我找不到任何关于它的文档。

它有什么作用?它是否与任何预定义的 StringComparer 匹配,例如 Ordinal 或 CurrentCulture?

简短的回答是 序数 但要证明它需要一些挖掘。

首先,Dictionary 的默认构造函数 docs 说:

Initializes a new instance of the Dictionary<TKey,TValue> class that [...] uses the default equality comparer for the key type.

EqualityComparer.Default 文档 say:

The Default property checks whether type T implements the System.IEquatable interface and, if so, returns an EqualityComparer that uses that implementation. Otherwise, it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

由于 System.String 执行 not implement System.IEquatable, Default should use its Object.Equals and Object.GetHashCode which perform 序数比较:

Remarks

This method performs an ordinal (case-sensitive and culture-insensitive) comparison.