字典Dictionary<TKey,TValue>的用法示例

203 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

Dictionary<TKey,TValue>是泛型的一种用法,所有TKey和TValue可以是任何类型。其中,TKey代表字典中键的类型,TValue代表字典中值的类型。 声明有关具体的Dictionary<TKey,TValue>实例时,需要传入真实类型,如下代码中的TKey是string型,TValue是int型。

using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(ParticleSystem))]
public class test : MonoBehaviour
{
    void Start()
    {
        Dictionary<string, int> dic = new Dictionary<string, int>();
        dic.Add("Ben", 1);  //字典添加元素
        dic.Remove("Ben");  //删除Key为"Ben"的元素
        dic.Clear(); //清除所有元素

        //遍历字典
        foreach (var item in dic)
        {
            Debug.Log(item.Key + item.Value);
        }
        foreach(KeyValuePair<string,int> kvp in dic)    //利用KeyValuePair<TKey,TValue>
        {
            Debug.Log(kvp.Key + kvp.Value);
        }
        foreach(string key in dic.Keys) //通过键的集合取值
        {
            Debug.Log(key + dic[key]);  //dic[key]:可以通过key索引value
        }
        foreach(int value in dic.Values)    //直接取值
        {
            Debug.Log(value);
        }
        //利用for的方法遍历
        List<string> list = new List<string>(dic.Keys);
        for (int i = 0; i < dic.Count; i++) //dic.count:dic中的元素个数
        {
            Debug.Log(list[i] + dic[list[i]]);
        }
    }

}