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

C# WinForm循环测试代码编译失败及内存溢出异常求助

问题修复说明

1. 编译失败原因

  • 事件签名错误:button4_Click 方法的签名不符合WinForm控件事件的标准格式,多了自定义参数string textLine,系统无法将这个方法绑定到按钮的Click事件,直接导致编译不通过。
  • 无效的图片加载:类字段Image dog= Image.FromFile(@"C:\Users\Empiric Library\source\repos\PictureBox\PictureBox\Form1.cs"); 这里你加载的是C#源代码文件,不是图片格式,GDI+无法解析为Image对象,要么删除这行无用代码,要么改成正确的图片路径。
  • (如果项目未创建Form2)Form2_Click方法里实例化Form2会报错,要么删除这部分无用代码,要么先在项目里新建Form2窗体。

2. System.OutOfMemoryException 内存溢出原因

  • 重复加载图片未释放资源:你在button1_Click、button2_Click里每次点击都重复调用Image.FromFile加载6张图片到Bully数组,旧的Image对象没有被Dispose释放,GDI+资源占用会持续累积,点击几次就会触发内存溢出。
  • 非图片格式加载错误:前面提到的dog字段加载cs源代码文件的操作,GDI+尝试解析非图片格式文件时也会触发内存异常。

3. 索引越界原因

  • 数组访问顺序错误:button1_Click里你先执行int i=0; pictureBox1.Image = Bully[i];,这时候Bully数组还未赋值全为null,且你后续只给Bully[0]到Bully[5]赋值,如果循环时num2输入超过5,就会访问Bully[6]及以上不存在的元素,直接触发越界报错。
  • button2_Click里的for循环用了i<=num2,且num1未赋值时默认是0,如果num2输入超过5,同样会访问数组不存在的下标。
  • 图片路径问题:如果你的Bully1~6.jpeg没有放到程序生成的exe同级目录(默认是bin/Debug或者bin/Release文件夹),Image.FromFile找不到文件也会触发报错。

修复后的代码参考

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace PictureBox
{
    public partial class Form1 : Form
    { 
        int num1, num2;
        // 只初始化6个元素,对应你现有6张图片
        Image[] Bully = new Image[6];
        int randomNum;

        public Form1()
        {
            InitializeComponent();
            // 窗体初始化时只加载一次图片,不要每次点击按钮都重复加载
            LoadBullyImages();
        }

        // 单独封装图片加载逻辑,全局只执行一次
        private void LoadBullyImages()
        {
            // 建议把图片路径换成绝对路径,或者确认图片放到exe同级目录
            string imgPath = @"C:\Users\Empiric Library\source\repos\PictureBox\PictureBox\";
            Bully[0] = Image.FromFile(Path.Combine(imgPath, "Bully1.jpeg"));
            Bully[1] = Image.FromFile(Path.Combine(imgPath, "Bully2.jpeg"));
            Bully[2] = Image.FromFile(Path.Combine(imgPath, "Bully3.jpeg"));
            Bully[3] = Image.FromFile(Path.Combine(imgPath, "Bully4.jpeg"));
            Bully[4] = Image.FromFile(Path.Combine(imgPath, "Bully5.jpeg"));
            Bully[5] = Image.FromFile(Path.Combine(imgPath, "Bully6.jpeg"));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int i = 0;
            // 先判断输入值合法性,不能超过数组最大下标5
            if (int.TryParse(textBox1.Text, out num1) && int.TryParse(textBox2.Text, out num2))
            {
                // 加边界校验,num2最大不能超过5
                num2 = Math.Clamp(num2, 0, 5);
                while (i < num2)
                {
                    MessageBox.Show("i=" + i);
                    pictureBox1.Image = Bully[i];
                    i++;
                }
            }
        }

        // 不需要Form2可以直接删除这段代码
        //private void Form2_Click(object sender, EventArgs e)
        //{
        //    Form2 form2 = new Form2();
        //    form2.Show();
        //    this.Hide();
        //}

        private void button2_Click(object sender, EventArgs e)
        {
            if (int.TryParse(textBox1.Text, out num1) && int.TryParse(textBox2.Text, out num2))
            {
                // 边界校验,避免越界
                num1 = Math.Clamp(num1, 0, 5);
                num2 = Math.Clamp(num2, num1, 5);
                for (int i = num1; i <= num2; i++)
                {
                    MessageBox.Show("Bully Number= " + i);
                    pictureBox1.Image = Bully[i];
                }
            }
        }
        private double Average(int num1, int num2)
        {
            double result = (num1 + num2) / 2.0;
            return result;
        }
        private void avg1_Click(object sender, EventArgs e)
        {
            double res = Average(1, 100);
            textBox4.Text = res.ToString();
        }

        // 修正button4的事件签名,删除多余的textLine参数
        private void button4_Click(object sender, EventArgs e)
        {
            // 用using自动释放StreamReader资源,无需手动Close
            using (StreamReader fileIn = new StreamReader(@"C:\Users\Empiric Library\source\repos\PictureBox\PictureBox\Form1.cs"))
            {
                string textLine = fileIn.ReadLine();
                MessageBox.Show("From File ..." + textLine);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            // 注意:原逻辑直接覆盖Form1.cs源代码,运行后会清空你写的代码,这里改成写入test.txt文件
            string outputPath = @"C:\Users\Empiric Library\source\repos\PictureBox\PictureBox\test.txt";
            using (StreamWriter FileOut = new StreamWriter(outputPath))
            {
                string str = "BullyProof";
                int number = 16;
                FileOut.WriteLine(str);
                FileOut.WriteLine(number);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Random random = new Random();
            randomNum = random.Next(1, 42);
            textBox3.Text = randomNum.ToString();
        }

        // 窗体关闭时释放所有图片资源,避免内存泄漏
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            foreach (var img in Bully)
            {
                img?.Dispose();
            }
        }
    }
}

额外注意事项

  • 所有实现了IDisposable接口的对象(Image、StreamReader、StreamWriter)都建议用using包裹,或者用完手动调用Dispose释放资源,避免内存泄漏。
  • 输入的图片索引范围控制在0-5,代码里已经加了Math.Clamp做边界校验,避免索引越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:15:03