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
原创粉丝点击