• 【Unity开发总结】C# 闭包陷阱


    0 问题

    在项目中动态地监听一组按钮,要求为按钮 i 注册函数 ActiveBlueprint(i) (带一个 int 参数的函数),初始代码如下:

    private void Awake()
    {
        // 初始化所有界面和对应按钮,监听按钮
        blueprints = new List<GameObject>();
        blueprintButtons = new List<Button>();
        for (int i = 0; i < panelNumber; ++i)
        {
            //Debug.Log("Blueprint" + i.ToString().PadLeft(2, '0'));
            blueprints.Add(transform.Find("Blueprint" + i.ToString().PadLeft(2, '0')).gameObject);
            blueprintButtons.Add(transform.Find("MainPanel/Button" + i.ToString().PadLeft(2, '0')).GetComponent<Button>());
            blueprintButtons[i].onClick.AddListener(() =>
            {
                ActiveBlueprint(i);
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    1 闭包陷阱1

    由于使用了 lambda 表达式作为 AddListener 的参数,变量 i 成为了被 lambda 表达式捕获的外部变量,所以变量 i 将不会被作为垃圾回收,直至引用变量的委托符合垃圾回收的条件2

    i 的最终取值是 panelNumber,这导致所有按钮都被注册了 ActiveBlueprint(panelNumber),和需求不符,解决方法是在每一轮循环中都定义新的变量,这样每一次 lambda 表达式都捕获了不同的变量,避免闭包陷阱。

    2 解决

    private void Awake()
    {
        // 初始化所有界面和对应按钮,监听按钮
        blueprints = new List<GameObject>();
        blueprintButtons = new List<Button>();
        for (int i = 0; i < panelNumber; ++i)
        {
            //Debug.Log("Blueprint" + i.ToString().PadLeft(2, '0'));
            blueprints.Add(transform.Find("Blueprint" + i.ToString().PadLeft(2, '0')).gameObject);
            blueprintButtons.Add(transform.Find("MainPanel/Button" + i.ToString().PadLeft(2, '0')).GetComponent<Button>());
            // 避免闭包陷阱
            int j = i;
            blueprintButtons[j].onClick.AddListener(() =>
            {
                ActiveBlueprint(j);
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    1. https://www.cnblogs.com/pangjianxin/p/8400155.html ↩︎

    2. https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/operators/lambda-expressions ↩︎

  • 相关阅读:
    2022华数杯建模A题思路解析
    HDMI线EMI超标整改方案
    大二数据结构实验(排序算法)
    CENTURY模型应用
    Scala / Java - Guava Sets 高效实践
    【6 进程间通信】
    sublime text 显示空格
    2023前端大厂高频面试题之JavaScript篇(5)
    MySQL锁机制
    Compose加载本地图片和网络图片
  • 原文地址:https://blog.csdn.net/G0rgeoustray/article/details/126561583