You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#循环绑定按钮Click事件时捕获的line变量值为空问题排查

问题根因

这是C#中闭包变量捕获的典型问题:

  • 你在for循环头部定义的line变量,作用域覆盖整个循环过程,每次迭代只是更新这个变量的值,而不是创建新的变量
  • 所有按钮点击事件的匿名方法addtoNuts,捕获的都是同一个line变量的引用
  • 循环结束时reader.ReadLine()返回null赋值给line,所以所有按钮触发事件时读到的line都是null

解决方案

在循环体内额外声明一个局部变量,存储当前迭代的line值,让每个委托捕获独立的局部变量即可。同时你原本的代码存在多余的字符串拼接再拆分操作,直接遍历Directory.GetFiles返回的数组更简洁可靠。

修正后代码

List<string> nuts = new List<string>();

public fileSelector()
{
    InitializeComponent();
    string videoDir = Path.Combine(Directory.GetCurrentDirectory(), "videos");
    if (Directory.Exists(videoDir))
    {
        // 直接获取所有wav文件路径数组,不用拼接再拆分
        string[] wavFiles = Directory.GetFiles(videoDir, "*.wav");
        foreach (string fullPath in wavFiles)
        {
            // 直接取文件名,不用手动替换路径
            string fileName = Path.GetFileName(fullPath);
            Trace.WriteLine(fileName);

            TextBlock name = new TextBlock()
            {
                Text = fileName.Replace("_", " ").Replace(".wav", ""),
                FontSize = 20,
                Width = 500,
                HorizontalAlignment = HorizontalAlignment.Left,
                Foreground = Brushes.White
            };
            fileList.Children.Add(name);

            Button add = new Button() {
                Height = 45,
                Width = 45,
                Content = new Image
                {
                    Source = new BitmapImage(new Uri(Path.Combine(Directory.GetCurrentDirectory(), "Images/newPlaylist.png"))),
                    VerticalAlignment = VerticalAlignment.Center
                }
            };
            
            // 循环内定义局部变量,每个委托捕获独立的变量
            string currentFileFullPath = fullPath.Replace("\\", "/");
            void addtoNuts(object sender, RoutedEventArgs e)
            {
                nuts.Add(currentFileFullPath);
                Trace.WriteLine(string.Join("\t", nuts));
            }
            add.Click += addtoNuts;
            
            fileList.Children.Add(add);
        }
    }
}

内容的提问来源于stack exchange,提问作者repolz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:54:04