每天看会儿书,学习一点巩固一点知识. 这篇是相应的练习
迭代变量的值是只读的,所以它不能改变.但是对于值类型和引用类型数组而言效果不一样.对于值类型数组,在用迭代变量表述数组元素的时候,我们不能改变它.对于引用类型数组,我们仍然不能改变迭代变量,但是迭代变量只保存了数据的引用,而不是数据本身,因此,虽然不能改变引用,但我们可以用过迭代变量改变数据.
要牢记迭代变量是只读的,所以想要在 foreach中 给 var 赋值或初始化都是不可行的.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrayTest : MonoBehaviour
{
class A//做一个引用类
{
public int ttt = 1;
}
int count;//三维数组计数器
int staCount;//交错数组的计数器
int[,,] array = new int[2, 3, 4] {
{ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } },
{ { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, { 21, 22, 23, 24 } }//声明一个三维数组
};
int[][,] starray = new int[3][,];//声明一个带二维数组的交错数组
A[][] staA = new A[2][];//声明一个引用类型的交错数组
void Start()
{
Debug.Log("引用类型使用foreach打印,调用属性");
staA[0] = new A[3] { new A(), new A(), new A() };
staA[1] = new A[2] { new A(), new A() };
foreach (var item in staA)//执行流程和for还是类似的,是一层一层的循环;迭代变量的值是只读的,所以它2不能改变.但是对于值类型和引用类型数组而言效果不一样.对于值类型数组,在用迭代变量表述数组元素的时候,我们不能改变它.对于引用类型数组,我们仍然不能改变迭代变量,但是迭代变量只保存了数据的引用,而不是数据本身,因此,虽然不能改变引用,但我们可以用过迭代变量改变数据.
{
Debug.Log("下一张表");
int i = 2;
foreach (A csa in item)//始终记住foreach里面是迭代引用,是只读的,不可写,但是可以对引用下的属性写.
{
csa.ttt = 5 * i;
Debug.Log("cas.ttt:" + csa.ttt);
i++;
}
}
for (int i = 0; i < starray.GetLength(0); i++)
{
starray[i] = new int[2, 2];
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
starray[i][j, k] = i + j + k;
}
}
}
Debug.Log("for循环打印交错数组");
for (int i = 0; i < starray.GetLength(0); i++)
{
for (int j = 0; j < starray[i].GetLength(0); j++)
{
for (int k = 0; k < starray[i].GetLength(1); k++)
{
starray[i][j, k]++;
Debug.Log(string.Format("starray[{0}][{1},{2}]:{3}", i, j, k, starray[i][j, k]));
}
}
}
Debug.Log("foreach打印交错数组");
foreach (var item in starray)
{
Debug.Log("新的一组二维数组");
foreach (int array in item)
{
staCount += array;
Debug.Log(string.Format("array:{0},staCount:{1}", array, staCount));
}
}
Debug.Log("````````````````````````````交错多维数组分割线`````````````````````````````````````````");
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
for (int k = 0; k < array.GetLength(2); k++)
{
Debug.Log(string.Format("array[{0},{1},{2}]:{3}", i, j, k, array[i, j, k]));
}
}
}
foreach (var item in array)
{
count += item;
Debug.Log("item:" + item + "," + "count:" + count);
}
}
}
对for循环的灵活运用
void Start()
{
bool randbool;
int x = 94;
for (; randbool = Random.value < 0.5f; )
{
Debug.Log("x:" + x);
if (x == 88) break;
x = Random.Range(87, 90);
}
}
for(p1;p2;p3){}
p1初始化,整个for循环只进来一次,然后判断p2,p2是一个bool表达式当然也可以是bool值, 如果为真则进入 {}语句块,如果为false则跳出,不写的话默认为true.语句块执行完毕后,则执行p3,然后 p2,语句块,依次循环,直至跳出循环.