首页 新闻 会员 周边

C# Dictionary中构造函数的问题

0
悬赏园豆:5 [已解决问题] 解决于 2014-09-05 15:21

  按照MSDN的说法

   Dictionary<stringstring> openWith = 
                                 new Dictionary<stringstring>(4);

其中构造函数中的INT参数应该是限制其容器大小的,按照msdn的demo,执行,其中我多add了一个元素没为什么输出是5个,难道这个参数不这么用,请高手解答
using System;
  using System.Collections.Generic;
  
  public class Example
  {
      public static void Main()
      {
          // Create a new dictionary of strings, with string keys and
  
          // an initial capacity of 4.
  
          Dictionary<string, string> openWith = 
                                 new Dictionary<string, string>(4);
  
          // Add 4 elements to the dictionary. 
  
          openWith.Add("txt", "notepad.exe");
          openWith.Add("bmp", "paint.exe");
          openWith.Add("dib", "paint.exe");
          openWith.Add("rtf", "wordpad.exe");
          openWith.Add("raw", "wordpad.exe");
  
  
          // List the contents of the dictionary.
  
          Console.WriteLine();
          foreach( KeyValuePair<string, string> kvp in openWith )
          {
              Console.WriteLine("Key = {0}, Value = {1}", 
                 kvp.Key, kvp.Value);
          }
      }
  }
  
  /* This code example produces the following output:

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = wordpad.exe
 */
        
diorlv的主页 diorlv | 菜鸟二级 | 园豆:259
提问于:2014-09-05 15:18
< >
分享
最佳答案
0

这个应该算BUG或者一种容错吧,反正,你能添加N多,最后能输出的就最多只有4个。

此外,你调用count看是4还是5,你不使用foreach,直接索引第5个(索引号4)结果又如何?试验下就好。

收获园豆:5
519740105 | 大侠五级 |园豆:5810 | 2014-09-05 15:19

好的,谢谢,这种解释到时能接受

diorlv | 园豆:259 (菜鸟二级) | 2014-09-05 15:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册