堆栈跟踪中 Dictionary`2 的含义

The meaning of Dictionary`2 in a stack trace

有时我会在堆栈跟踪中看到这个 `2。例如:

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key)

词典后面的`2是什么意思?

System.Collections.Generic.Dictionary`2表示类型为System.Collections.Generic.Dictionary,有两个类型参数。所以在这种情况下它意味着类型是System.Collections.Generic.Dictionary<TKey, TValue>,众所周知。

这就是 .Net 命名 类 的方式。初始声明

 Dictionary<K, V>

将变成 Dictionary'2 类型名称,其中 '2 表示 两个 泛型参数:

 // Dictionary`2 - two generic parameters
 Console.WriteLine(typeof(Dictionary<int, string>).Name);

 // List`1 - one generic parameter
 Console.WriteLine(typeof(List<int>).Name);

请比较:

 // IDictionary`2 - two generic parameters
 Console.WriteLine(typeof(IDictionary<int, string>).Name);

 // IDictionary - no generic parameters
 Console.WriteLine(typeof(System.Collections.IDictionary).Name);