目录
Dictionary Constructors,tvalue>
Dictionary.Item[ TKey ],tvalue>
Dictionary.TryAdd(TKey, TValue) ,tvalue>
Dictionary.Add(TKey, TValue),tvalue>
Dictionary.ContainsKey(TKey),tvalue>
Dictionary.ContainsValue(TValue) ,tvalue>
Dictionary.TryGetValue(TKey, TValue),tvalue>
该类在 System.Collections.Generic 命名空间。
Dictionary<TKey,TValue> 类 表示 键和值 的集合。 该类 被实现为哈希表。
Dictionary <TKey,TValue>中的每个键必须是唯一的。 键不能为null,但如果其类型 TValue 是引用类型,则 TValue可以为null。 但是每个值不需要唯一,意思就是说不一样的键可以映射相同的值。
- 类型参数 TKey 表示字典中的 键的类型。
- 类型参数 表示 TValue 字典中的值的类型。
Dictionary<TKey,TValue> Constructors
public Dictionary (); public Dictionary (int capacity); public Dictionary (System.Collections.Generic.IDictionary<TKey,TValue> dictionary);
static void Main(string[] args) { // 使用默认的构造函数初始化 Dictionary 类对象,该对象为空,并且具有默认容量 Dictionary<string, string> value = new Dictionary<string, string>(); // 为 Dictionary 类对象指定初始的容量大小 Dictionary<string, string> vv = new Dictionary<string, string>(5); Dictionary<string, string> copy =new Dictionary<string, string>(vv); // copy 是 vv 的副本 }
Propertys
Dictionary<TKey,TValue>.Count
public int Count { get; }
- 获取Dictionary <TKey,TValue>中包含的键/值对的数量。(只读)
- 当前容量始终大于或等于 Count。 如果 Count 在添加元素时超出容量,则在复制旧元素和添加新元素之前,通过自动重新分配内部数组来增加容量。
- 获取此属性的值是 o (1) 操作。
WriteLine(vv.Count);
Dictionary<TKey,TValue>.Item[ TKey ]
public TValue this[TKey key] { get; set; }
- 通过 键key 来获取或设置与指定键关联的值。
- key 不能为
null
,如果TValue
是引用类型。则 key 映射的值可以是 null- 参数TValue: 如果未找到指定的键,则 get 操作将引发 KeyNotFoundException ,而 set 操作将使用指定的键创建新元素
- 如果
参数 key
为null
。抛出 ArgumentNullException- 可以使用 Item [TKey] 属性通过设置 Dictionary <TKey,TValue> 中不存在的键来添加新元素。设置属性值时,如果键位于Dictionary <TKey,TValue>中,则与该键关联的值将替换为指定的值。如果该键不在Dictionary <TKey,TValue>中,则键和值将添加到Dictionary 中。相反,Add方法不会修改现有元素。
- 获取或设置此属性的值接近 o (1) 操作。
static void Main(string[] args) { Dictionary<string, string> vv = new Dictionary<string, string>(5); vv.Add("txt", "notepad.exe"); vv.Add("bmp", "paint.exe"); vv.Add("dib", "paint.exe"); vv.Add("rtf", "wordpad.exe"); vv["rdsadtf"] = "huang"; // vv 中没有键rdsadtf,那么会创建一个键其对应值 huang 的新元素 Console.WriteLine(vv["sad"]); // vv 中没有该键,将发生异常 }