using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// C# Dictionary 語法測試
/// 遍歷容器
/// </summary>
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<int, StudentInfo> studentInfos;
public Dictionary_Test()
{
/// 賦值,初始化
studentInfos = new Dictionary<int, StudentInfo>();
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);
}
}
/// <summary>
/// C# Dictionary 遍歷
/// </summary>
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<int, StudentInfo> 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<int> keys = new List<int>(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));
}
}
}
C# Dictionary 遍歷
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.