【发布时间】:2011-01-05 10:12:18
【问题描述】:
在 C# 中如何使用 foreach 循环?
【问题讨论】:
在 C# 中如何使用 foreach 循环?
【问题讨论】:
class ForEachTest
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}
【讨论】:
有时解决方案非常简单。信息可以找到here
一个例子:
// Use a string array to loop over.
string[] ferns = { "Psilotopsida", "Equisetopsida", "Marattiopsida", "Polypodiopsida" };
// Loop with the foreach keyword.
foreach (string value in ferns)
{
Console.WriteLine(value);
}
更多信息和示例可以在这里找到:http://dotnetperls.com/foreach
【讨论】:
foreach 语句为数组或对象集合中的每个元素重复一组嵌入语句。 foreach 语句用于遍历集合以获取所需的信息,但不应用于更改集合的内容以避免不可预知的副作用。
例子:
class ForEachTest {
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}
MSDN:https://msdn.microsoft.com/en-us/library/ttw7t8t6(v=vs.80).aspx
【讨论】: