C# Dictionary 遍历 -- Unity

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// 
///  C# Dictionary 语法测试
///  遍历容器
/// 
public class Dictionary_Test
{
    private class StudentInfo
    {
        public StudentInfo(int num, string na, int ag, float he)
        {
            number = num;
            name = na;
            age = ag;
            height = he;
        }

        public override string ToString()
        {
            return string.Format("number = {0},name = {1},age = {2},height = {3}", number, name, age, height);
        }

        public int number;
        public string name;
        public int age;
        public float height;
    }

    private Dictionary studentInfos;

    public Dictionary_Test()
    {
        /// 赋值,初始化
        studentInfos = new Dictionary();
        for (int i = 0; i < 5; ++i)
        {
            int number = 1000 + i;
            StudentInfo info = new StudentInfo(number, "Ab_" + i.ToString(), i + 10, 1.7f);
            studentInfos.Add(number, info);
        }
    }

    /// 
    /// C# Dictionary 遍历
    /// 
    public void TraverseContainer()
    {
        /// 遍历方法1
        foreach (var item in studentInfos)
        {
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法1:number = {0},StudentInfo = ({1})", item.Key, item.Value));
        }

        /// 遍历方法2
        foreach (KeyValuePair keyPair in studentInfos)
        {
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法2:number = {0},StudentInfo = ({1})", keyPair.Key, keyPair.Value));
        }

        /// 遍历方法3
        foreach (int key in studentInfos.Keys)
        {
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法3:number = {0},StudentInfo = ({1})", key, studentInfos[key]));
        }

        /// 遍历方法4
        List keys = new List(studentInfos.Keys);
        for (int i = 0, count = keys.Count; i < count; ++i)
        {
            int key = keys[i];
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法4:number = {0},StudentInfo = ({1})", key, studentInfos[key]));
        }

        /// 遍历方法5
        foreach (StudentInfo value in studentInfos.Values)
        {
            /// unity环境中的输出
            Debug.Log(string.Format("遍历方法5:StudentInfo = ({0})", value));
        }
    }
}

 

你可能感兴趣的:(Unity,C#,语法,C#,Dictionary,遍历)