闭包概念
内层的函数可以引用包含在它外层的函数变量,即使外层函数的执行已经终止。但,该变量的值并非变量创建时的值,而是在外层函数内的最终值。
使用场景
闭包主要使用在访问外层函数定义的变量上。由于C#中有委托和lambda函数,所以C#可以在方法体内嵌套委托或lambda表达式,此时就形成了闭包,闭包可以帮助我们轻松地访问外层函数定义的变量。
以下是闭包(嵌套)代码:
void CloserMothed(int v1)
{
void CloserMothedChild(int v2)
{
int endValue = v1 + v2;
}
}
错误使用后存在坑的情况:
public class Closer : MonoBehaviour
{
public List<Button> btns;
void Start()
{
for (int i = 0; i < btns.Count; i++)
{
btns[i].onClick.AddListener(() => {
OnClick(i);//i始终是btns.Count
});
}
}
void OnClick(int index)
{
print(index);
}
}
// 输出:
// btns.Count
// btns.Count
// btns.Count
修正后:
public class Closer : MonoBehaviour
{
public List<Button> btns;
void Start()
{
for (int i = 0; i < btns.Count; i++)
{
int index = i;//用一个变量来接收i,这样内函数使用index就是我们想要的结果了。
btns[i].onClick.AddListener(() => { OnClick(index);});
}
}
void OnClick(int index)
{
print(index);
}
}
// 输出:
// 1
// 2
// 3
// 。。。