您的位置:首页 > 编程语言 > C#

c#中的foreach语句

2012-10-07 22:09 218 查看
c#中foreach主要用于遍历集合中的每个元素,数组也属于集合类型,因此foreach语句允许用于数组元素的遍历。

语法形式:

foreach(类型 标识符 in 集合表达式)

标识符——foreach循环的迭代变量,只在foreach语句中有效,并且是一个只读局部变量,即在foreach语句中不能改写这个迭代变量。它的类型应与集合的基本类型一致。

集合表达式——被遍历的集合,如数组。

在foreach语句中执行期间,迭代变量按集合元素的顺序依次将其内容读入。对数组而言foreach语句可用于对数组中的每一个元素执行一遍循环体语句。

实例:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace foreach的练习

{

class Program

{

public static void Main(string[] args)

{

int pass;

int[] score = new int[] { 98, 76, 87, 65, 55, 68, 57, 84, 96, 100 };

pass = 0;

foreach (int x in score)

if (x >= 60)

{

pass++;

Console.Write("{0,4:d}", x);

}

Console.WriteLine("\n及格率:{0:p}", (double)pass / score.Length);

Console.Read();

}

}

}

本文出自 “一切尽在IT” 博客,请务必保留此出处http://mzy123.blog.51cto.com/3386085/1016603
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: