使用泛型类型'System.Collections.Generic.Dictionary <TKey,TValue>'需要2个类型参数

Duk*_*ade 6 c# dictionary

我收到错误使用泛型类型'System.Collections.Generic.Dictionary <TKey,TValue>'需要使用以下代码行的2个类型参数:

this._logfileDict = new Dictionary();
Run Code Online (Sandbox Code Playgroud)

我只是想在我的代码中有一个明确的_logfileDict没有条目,所以这就是为什么我给它分配一个新的Dictionary,它将是空的,但是如果有人知道一些代码,我可以用它来清空_logfileDict.它只是一个字典声明如下:

private Dictionary<string, LogFile> _logfileDict;
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢!

Joh*_*mer 13

您收到此错误的原因是您尝试使用Dictionary<TKey, TValue>需要泛型类型参数的Dictionary类,并且没有不需要泛型类型参数的类.

当使用使用泛型类型参数的类时,只要声明或实例化处理类的变量,就需要提供要使用的类型.

更换:

this._logfileDict = new Dictionary();
Run Code Online (Sandbox Code Playgroud)

附:

this._logfileDict = new Dictionary<string, LogFile>();
Run Code Online (Sandbox Code Playgroud)


jas*_*son 6

Dictionary.NET Framework中没有没有泛型参数的类型.在实例化和实例时必须显式声明类型参数Dictionary<TKey, TValue>.在您的情况下,_logfileDict声明为Dictionary<string, LogFile>,因此您必须在分配新实例时明确说明.因此,您必须这样分配给_logfileDict新实例:

this._logfileDict = new Dictionary<string, LogFile>();
Run Code Online (Sandbox Code Playgroud)

(但是,请注意,System.Collections.Hashtable如果您不想指定键和值的类型,则.NET Framework中有一个.)