publicclassPerson{publicstring name;publicPerson(string name){this.name = name;}}publicclassTest:MonoBehaviour{privatePerson[] p =newPerson[2];//数组中的元素是引用类型,就必须为每个数组元素分配内存privatePerson[] p2 ={newPerson("ss"),newPerson("aa")};
二维数组和三维数组
//尚未赋值的二维数组privateint[,] two =newint[3,3];//数组索引器初始化二维数组privateint[,] twoindex ={{1,2},{2,4}};//三维数组privateint[,,] three ={{{1,2},{3,5}},{{2,3},{3,6}}};
//复制数组//因为数组是引用类型,所以将一个数组变量赋予另一个数组变量,就会得到两个引用同一数组的变量。而复制数组//会使数组实现ICloneable,这个接口定义的Clone()方法会创建数组的浅表副本privateint[] a ={1,2};privateint[] b =newint[2];privatevoidStart(){
b = a;
a[1]=3;print(b[1]);//直接等于共用的是一个内存 结果为3
b =(int[])a.Clone();
a[1]=4;print(b[1]);//使用Clone方法,值类型会重新复制一份,但引用类型仍然共用 结果为4,不受A数组值变化的影响//要想实现包含引用类型的数组的深层副本,就必须迭代数组并创建新对象}
foreach语句
//IEnumerator接口//IEnumerator定义了Current属性,来返回光标所在的元素,该接口的MoveNext()方法移动到集合的下一个元素上。如果有则返回True,否则返回False//Foreach转换为IEnumerator接口的方法和属性privatestaticList<p> listP =newList<p>();classp{}privateIEnumerator<p> _enumerator = listP.GetEnumerator();privatevoidGo(){while(_enumerator.MoveNext()){p p = _enumerator.Current;}}