集合特点:
一种数据容器,一种数据结构
容纳多个数据,大小可变,空间不一定连续
集合两大体系:非泛型集合,泛型集合
非泛型缺点:
- 性能不好,因为可能发生装箱。
- 类型不安全,可能会发生类型转换的异常。
- 使用不方便,用的时候需要手动做类型转换。
非泛型 泛型
列表 ArrayList List< T >
字典 Hashtable Dictionary< TKey,TValue >
栈 Stack (后进先出) Stack<T>
队列 Queue(先进先出) Queue <T>
//非泛型命名空间
using System.Collections;
//泛型命名空间
using System.Collections.Generic;
列表操作
public class ArrayListTest : MonoBehaviour{
private ArrayList list = new ArrayList();//非泛型集合
private List<string> list02 = new List<string>();//泛型集合(需指定类型)
private List<int> listInt = new List<int>() { 1, 10, 5, 100 };
public GameObject cube;
private void Start(){
list02.Add("赵六");
listInt.Sort();
foreach (int item in listInt)
{
print("排序 : " + item);
}
list.Add(1); //非泛型列表可以装任意类型元素
list.Add("张三");
list.Add("李四");
list.Add(cube);
//判断集合中是否含有“张三”,并将“张三”移除
if (list.Contains("张三"))
list.Remove("张三");
//从索引1位置插入“王五”元素
list.Insert(1, "王五");
list.Count;//列表元素个数
//从索引0位置移除2个元素
list.RemoveRange(0, 2);
for (int i = 0; i < list.Count; i++){
print("1: " + list[i]);
}
}
字典操作
/// <summary>
/// 非泛型字典(一键对应一值)
/// </summary>
public class HashtableTest : MonoBehaviour
{
private Hashtable table = new Hashtable();
private void Start()
{
// 主键 //子键
table.Add("张三", 111);//电话 QQ 地址
table.Add("李四", 222);
//print(table["张三"]);
//foreach (var num in table.Values)
//{
// print("值 : " + num);
//}
foreach (var num in table.Keys)
{
print("key: " + num + " Value: " + table[num]);
}
}
}
/// <summary>
/// 泛型字典(字典嵌套字典)
/// </summary>
public class DicTest : MonoBehaviour
{
//主键 子键 值(可以多重嵌套)
private Dictionary<string, Dictionary<string, string>> myDic
= new Dictionary<string, Dictionary<string, string>>();
private void Start()
{
myDic.Add("张三", new Dictionary<string, string>());
myDic["张三"].Add("QQ", "12345");
myDic["张三"].Add("地址", "北京");
print(myDic["张三"]["地址"]);
}
}
栈:先进后出
public class StackTest : MonoBehaviour
{
/*主菜单->选项->游戏选项->难度调节->简单
* 逐层压栈,逐层弹栈,最后一个(主菜单),只读不弹
*/
private Stack stack = new Stack();
private void Start()
{
//逐层压栈
stack.Push("主菜单");
stack.Push("选项");
stack.Push("游戏选项");
stack.Push("难度调节");
stack.Push("简单");
//逐层弹栈
while (stack.Count > 1)
{
print("弹栈 : " + stack.Pop());
}
print("只读不弹 : " + stack.Peek());
//stack.Push("你好");//压栈
//print("读取并移除顶部对象 : " + stack.Pop());//弹栈
//print("读取但不移除顶部对象(读栈顶): " + stack.Peek());//读栈顶
}
}
队列:先进先出
public class QueueTest : MonoBehaviour
{
private Queue queue = new Queue();
private void Start()
{
queue.Enqueue("入队");
print(queue.Dequeue());//出队
print(queue.Peek());//读队首
print(queue.Count);
}
}