C# 之 Dictionary 详解

时间:2025-04-17 15:25:09

▪ 说明

  • 必须包含名空间
  • Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)
  • 键必须是唯一的,而值不需要唯一的
  • 键和值都可以是任何类型(比如:string, int, 自定义类型等等)

可以简单将 Dictionary 理解为 键值对 数据的集合

▪ 常规使用方法

// 定义
Dictionary<string, string> dictExecutes = new Dictionary<string, string>();

// 添加元素
("bmp", "");
("dib", "");
("rtf", "");
("txt", "");

// 取值
("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);

// 改值
dictExecutes["rtf"] = "";
("For key = 'rtf', value = {0}.", dictExecutes["rtf"]);

// 遍历 KEY
foreach( string key in  ) ("Key = {0}", key);

// 遍历 VALUE
foreach( string value in  ) ("value = {0}", value);

// 遍历字典
foreach( KeyValuePair<string, string> kvp in dictExecutes ) ("Key = {0}, Value = {1}", , );
// 添加存在的元素
try{
    ("txt", "");
}catch( ArgumentException ){
    ("An element with Key = 'txt' already exists.");
}

// 删除元素
("doc");
if( !("doc") ) ("Key 'doc' is not found.");

// 判断键存在
if( ("bmp") ) ("An element with Key = 'bmp' exists.");

▪ 参数为其它类型

// 参数为其它类型 
Dictionary<int, string[]> dictOthers = new Dictionary<int, string[]>();

(1, "1,11,111".Split(','));
(2, "2,22,222".Split(','));

(dictOthers[1][2]);

▪ 参数为自定义类型

// 首先定义类
class DouCube
{
    private int _Code;
    public int Code { get{ return _Code; } set{ _Code = value; } }
    
    private string _Page;
    public string Page { get{ return _Page; } set{ _Page = value; } } 
}

// 声明并添加元素
Dictionary<int, DouCube> MyTypes = new Dictionary<int, DouCube>();

for( int i = 1; i <= 9; i++ ){
    DouCube elem = new DouCube();
    
     = i * 100;
     = "/" + () + ".html";
    
    (i, elem);
}

// 遍历元素
foreach( KeyValuePair<int, DouCube> kvp in MyTypes ){
    ("Index {0} Code:{1} Page:{2}", , , );
}