按照MSDN的说法
Dictionary<string, string> openWith = new Dictionary<string, string>(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 */
这个应该算BUG或者一种容错吧,反正,你能添加N多,最后能输出的就最多只有4个。
此外,你调用count看是4还是5,你不使用foreach,直接索引第5个(索引号4)结果又如何?试验下就好。
好的,谢谢,这种解释到时能接受