For faster navigation, this Iframe is preloading the Wikiwand page for Foreach循环.

Foreach循环

Foreach 循环(foreach loop)是计算机编程语言中的一种控制流程语句,通常用来循环遍历数组集合中的元素。

程序示例

[编辑]

C#

[编辑]

以下代码用于循环打印名称为myArray的整型数组中的每个元素。[1]

foreach (int x in myArray)
{
  Console.WriteLine(x);
}

C#不允许在foreach循环中改变数组或集合中元素的值(注:成员的值不受影响),如以下代码将无法通过编译。

foreach (int x in myArray)
{
  x++; //错误代码,因为改变了元素的值
  Console.WriteLine(x);
}

如果要让自定义的数据类型支持foreach循环,则该类型必须实现IEnumerable<T>接口,且存在对应此列表的IEnumerator<T>实现。 实际上,在.Net的底层(IL语言层面)而言,

foreach (var x in list) // x的类型为T
{ 
  ...
}

等价于如下代码:

using (var iterator = list.GetEnumerator()) // iterator的类型为IEnumerator<T>
{
  while ( iterator.MoveNext() ) 
  {
    var x = iterator.Current();
    ... // 本段代码中禁止修改x的值——编译器会报错
  }
}

它只是为了让用户更加易于使用的等价描述形式。

Java

[编辑]

Java语言从JDK 1.5.0开始引入foreach循环。[2]

以下代码用于循环打印myArray数组中的每个元素,java中的foreach循环使用for关键字,而非foreach

for (int x : myArray){
  System.out.println(x);
}

与C#不同的是,Java中运行以下代码不会编译出错,但是实际数组中的元素不会被修改。

for (int x : myArray){
  x++; 
 System.out.println(x);
}

C++

[编辑]

C++11擴展for的用法,增加了foreach功能,語法和Java一樣。

for (int x : myArray){
  cout << x << endl;
}

同時也有C++求值策略的功能,可以傳參考。

for (int& x : myArray){
  x = x * x;
}
for (int x : myArray){
  cout << x << endl;
}

参考資料

[编辑]
  1. ^ foreach、in (C# 參考). msdn.microsoft.com. [2015-10-16]. (原始内容存档于2015-01-12). 
  2. ^ The For-Each Loop. docs.oracle.com. [2015-10-16]. (原始内容存档于2015-06-22). 

参见

[编辑]
{{bottomLinkPreText}} {{bottomLinkText}}
Foreach循环
Listen to this article

This browser is not supported by Wikiwand :(
Wikiwand requires a browser with modern capabilities in order to provide you with the best reading experience.
Please download and use one of the following browsers:

This article was just edited, click to reload
This article has been deleted on Wikipedia (Why?)

Back to homepage

Please click Add in the dialog above
Please click Allow in the top-left corner,
then click Install Now in the dialog
Please click Open in the download dialog,
then click Install
Please click the "Downloads" icon in the Safari toolbar, open the first download in the list,
then click Install
{{::$root.activation.text}}

Install Wikiwand

Install on Chrome Install on Firefox
Don't forget to rate us

Tell your friends about Wikiwand!

Gmail Facebook Twitter Link

Enjoying Wikiwand?

Tell your friends and spread the love:
Share on Gmail Share on Facebook Share on Twitter Share on Buffer

Our magic isn't perfect

You can help our automatic cover photo selection by reporting an unsuitable photo.

This photo is visually disturbing This photo is not a good choice

Thank you for helping!


Your input will affect cover photo selection, along with input from other users.

X

Get ready for Wikiwand 2.0 🎉! the new version arrives on September 1st! Don't want to wait?