C# 中 foreach的用法 (补List 的 ForEach细节)
foreach有点像是for的增强版
在C#中有时候会遇到需要循环输出的情况,比如这样:
using Syatem using System.Collections; using System.Collections.Generic; class one { int[] A = { 1, 2, 3, 4, 5 }; void Main() {
//for for (int i = 0; i < A.Length; i++) Console.WriteLine(A[i]);
//foreach foreach (int i in A) Console.WriteLine(i); } }
可以看出,当不需要麻烦的操作的时候,不需要针对第 i 元素进行奇怪的操作时,foreach提高了写代码的整洁和效率;
注:
1.foreach中的 i 就是A中的元素,如果A是字符串,则应该写为
foreach (char i in A) Console.WriteLine(i);
2.不要在foreach中试图增删,这样会报异常!需使用for!
3.List中有一个ForEach,可以实现在循环内增删,关于此还有挺多可以说的:
List中ForEach是有委托的:要对 Action<T> 的每个元素执行的 List<T> 委托
标准写法: public void ForEach (Action<T> action); ,然后官方给出了一个示例,由此就可以看出用法了:

1 using System; 2 using System.Collections.Generic; 3 4 class Program 5 { 6 static void Main() 7 { 8 List<String> names = new List<String>(); 9 names.Add("Bruce"); 10 names.Add("Alfred"); 11 names.Add("Tim"); 12 names.Add("Richard"); 13 14 // Display the contents of the list using the Print method. 15 names.ForEach(Print); 16 17 // The following demonstrates the anonymous method feature of C# 18 // to display the contents of the list to the console. 19 names.ForEach(delegate(String name) 20 { 21 Console.WriteLine(name); 22 }); 23 } 24 25 private static void Print(string s) 26 { 27 Console.WriteLine(s); 28 } 29 } 30 /* This code will produce output similar to the following: 31 * Bruce 32 * Alfred 33 * Tim 34 * Richard 35 * Bruce 36 * Alfred 37 * Tim 38 * Richard 39 */
by the way,此操作是O(n)操作。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY