C#foreach用法
沐马仁 2019-07-24 11:44:05 foreach循环用于列举出集合中所有的元素,使用foreach可以迭代数组或者一个集合对象。程>
每一次循环时,从集合中取出一个新的元素值,放到只读变量中去,如果括号中的整个表达式返回值为true,foreach块中的语句就能执行。一旦集合中的元素都应经被访问到,整个表达式的值为false,控制流程就转入到foreach块后面的执行语句。
<遍历数组>
class Program { static void Main(string[] args) { int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; foreach (int i in array) { Console.WriteLine(i); } } } 它实现了对数组元素的遍历,遍历之前需要指定元素的类型
12345678910111213
//结果 1 2 3 4 5 6 7 8 9
12345678910
<遍历字符串>
class Program { static void Main(string[] args) { string test = "Hello,world!"; foreach (char i in test) { Console.WriteLine(i); } } }
1234567891011
//结果 H e l l o , w o r l d !
12345678910111213
将i的类型char换成int
//结果 72 101 108 108 111 44 119 111 114 108 100 33 输出的结果是字符所对应的ASCII码值,说明这里进行了数据类型的隐式转换
1234567891011121314
<注释>
变量名用来存放该集合中的每个元素ArrayList或List是一个类,它可以让foreach去遍历
<举例>
class Program { static void Main(string[] args) { int count; Console.WriteLine("输入要登记的学生数"); count = int.Parse(Console.ReadLine()); string[] names = new string[count];//声明一个存放姓名的字符串数组,其长度等于提供的学生人数 for (int i = 0; i < names.Length; i++)//接受姓名 { Console.WriteLine("请输入第{0}个学生的姓名", i + 1); names[i] = Console.ReadLine(); } Console.WriteLine("已登记的学生如下"); foreach (string name in names)//显示姓名 { Console.WriteLine("{0}", name); } Console.ReadKey(); } }
123456789101112131415161718192021
<注意>:
foreach循环是只读的,不能遍历修改数据foreach循环是只进的,并且是一条一条循环的