• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一蓑烟雨
C/C++,Linux,语音技术
博客园    首页    新随笔    联系   管理    订阅  订阅
foreach和for

1、foreach循环与for循环输出结果比较,能达到一样的输出效果。

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ForeachApplication
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int[] a = { 1,5,9,20,16};
13 Console.WriteLine("使用foreach ....结果");
14 foreach (int i in a)
15 {
16 Console.WriteLine("{0}",i);
17 }
18 Console.WriteLine("使用for ....结果");
19 for (int j = 0; j < 5; j++)
20 Console.WriteLine("{0}",a[j]);
21 }
22 }
23 }

2、foreach与 for 的主要区别在于 foreach 循环对数组内容进行只读访问,所以不能改变任何元素的值。而for 循环可以,看下面代码:

foreachfor
 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ForeachApplication
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int[] a = { 1,5,9,20,16};
13 Console.WriteLine("使用foreach ....结果");
14 foreach (int i in a)
15 {
16 Console.WriteLine("{0}",i);
17 }
18 Console.WriteLine("使用for ....结果");
19 for (int j = 0; j < 5; j++)
20 // Console.WriteLine("{0}",a[j]);
21 {
22 if (a[j] > 10)
23 {
24 a[j] = 7;
25 }
26
27 }
28 Console.WriteLine("把数组中的大于10的数,修改成7后....输出结果");
29 foreach (int i in a)
30 {
31 Console.WriteLine("{0}", i);
32 }
33 }
34 }
35 }



posted on 2011-11-30 12:00  lovemu  阅读(287)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3