C#匿名方法之循环注册问题
来源:互联网 发布:windows 10未正确启动 编辑:程序博客网 时间:2024/06/06 02:06
C#匿名方法之循环注册问题
Demo:
void Demo() { List<Action> list = new List<Action>(); for (int i = 0; i < 5; i++) { list.Add(delegate { LogManager.Log(i + "\n"); } ); } foreach (Action action in list) { if (action != null) { action(); } } }
运行结果:
Test1:
void Test1() { List<GameObject> objs = new List<GameObject>(); for (int i = 0; i < 5; i++) { GameObject obj = new GameObject(); obj.name = "obj-" + i; objs.Add(obj); } List<Action> list = new List<Action>(); for (int i = 0; i < objs.Count; i++) { list.Add(delegate() { LogManager.Log(objs[i].name + "\n"); } ); } foreach (Action action in list) { if (action != null) { action(); } } }
运行结果: GG...
System.ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
at System.Collections.Generic.List`1[UnityEngine.GameObject].get_Item (Int32 index) [0x0000c] in /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633
Test2:
void Test2() { List<GameObject> objs = new List<GameObject>(); for (int i = 0; i < 5; i++) { GameObject obj = new GameObject(); obj.name = "obj-" + i; objs.Add(obj); } List<Action> list = new List<Action>(); for (int i = 0; i < objs.Count; i++) { int count = i; list.Add(delegate() { LogManager.Log(objs[count].name + "\n"); } ); } foreach (Action action in list) { if (action != null) { action(); } } }
运行结果:
完
1 0
- C#匿名方法之循环注册问题
- C#匿名函数之匿名方法与lambda表达式
- c#之委托、匿名方法、Lambda表达式
- C#基础之匿名方法实例教程
- C#匿名方法zz
- C#的匿名方法
- C#基础:匿名方法
- c# 匿名方法
- C#的匿名方法
- C#匿名方法
- C# 匿名方法 委托
- C#匿名方法
- c#匿名方法
- C# 匿名方法
- c#的匿名方法
- C#匿名方法
- C# 匿名方法
- c#匿名方法
- 一天搞定CSS(扩展):CSS Hack
- windows 下安装 NSClient++
- Intellij IDEA 创建GUI界面
- 初识.net界面程序(9)--LINQ To XML
- 编译ijkplayer-android源码
- C#匿名方法之循环注册问题
- 获取wifi密码的方式
- linux 增加用户 useradd 用法小结及配置文件说明
- C语言程序设计(16)
- static关键字
- 如何转载别人的博客文章
- 如何使用Android Studio打包混淆的Jar
- Code::Blocks 16.01 Debug方法
- LEETCODE 60. Permutation Sequence