【问题标题】:Using the generic type 'System.Collections.Generic.Dictionary< TKey, TValue>' requires 2 type arguments使用泛型类型 'System.Collections.Generic.Dictionary<TKey, TValue>' 需要 2 个类型参数
【发布时间】:2011-11-16 14:40:05
【问题描述】:

我收到错误使用泛型类型 'System.Collections.Generic.Dictionary' 需要 2 个类型参数,这行代码:

this._logfileDict = new Dictionary();

我只是想在我的代码中创建一个清晰的 _logfileDict,其中没有条目,这就是为什么我要为其分配一个新字典,该字典将为空,但如果有人知道一些代码,我可以用它来清空_logfileDict 否则。它只是一个声明如下的字典:

private Dictionary<string, LogFile> _logfileDict;

非常感谢任何帮助!

【问题讨论】:

  • 一旦您输入“= new”,IntelliSense 应该会为您指明正确的方向...
  • 答案在错误信息中。

标签: c# dictionary


【解决方案1】:

您收到此错误的原因是因为您尝试使用需要generic 类型参数的Dictionary&lt;TKey, TValue&gt; 类,并且没有不需要泛型类型参数的Dictionary 类。

当使用使用泛型类型参数的类时,您需要在声明或实例化处理该类的变量时提供要使用的类型。

替换:

this._logfileDict = new Dictionary();

与:

this._logfileDict = new Dictionary<string, LogFile>();

【讨论】:

  • 答案有点短,但还是正确的:)。
  • @jv42 同意,我已经更新了答案以包含更多信息和参考。
  • 哦,很好,现在这是一个非常好的答案:)
【解决方案2】:

在 .NET Framework 中没有没有泛型参数的类型 Dictionary。实例化Dictionary&lt;TKey, TValue&gt; 的实例时必须显式声明类型参数。在您的情况下,_logfileDict 被声明为Dictionary&lt;string, LogFile&gt;,因此您必须在分配它的新实例时明确声明这一点。因此,您必须为_logfileDict 分配一个新实例:

this._logfileDict = new Dictionary<string, LogFile>();

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

【讨论】:

    【解决方案3】:

    你需要指定两种类型:

    this._logfileDict = new Dictionary<string, LogFile>();
    

    【讨论】:

      【解决方案4】:

      试试这个..

       this._logfileDict = new Dictionary<string, LogFile>(); 
      

      值得一读字典和如何初始化,请go through this link了解更多关于字典的信息...

      【讨论】:

        【解决方案5】:

        你知道你的字典中的构造函数需要你的键类型和你的值类型,所以这就是你得到的错误。

        而且因为您的日志文件字典 def 具有字符串类型和日志文件类型,所以构造函数肯定是

        this._logfileDict = new Dictionary<string, LogFile>(); 
        

        这是一个空的(如您定义的那样清晰)字典,但它需要初始化此定义,以便在您向其中输入内容时,它可以键入检查

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 2016-06-17
          • 2017-12-05
          • 1970-01-01
          • 1970-01-01
          • 2021-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多