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

C# 向List存储鼠标点击坐标时仅保留最后一个元素问题求助

问题根因

你将List<String> myPoints的定义和实例化操作写在了pictureBox1_MouseDown点击事件的方法内部,每次触发点击事件时,程序都会创建一个全新的空List对象,当前坐标添加完成后,这个局部List对象会随着方法执行结束被回收,因此无法保留之前的点击记录。

修复步骤

  • 将List变量调整为类级别的字段,放在窗体类内部、所有方法的外部,整个程序运行过程中仅实例化一次
  • 点击事件内仅保留坐标赋值、追加到List的逻辑,不要重复实例化List

修复后代码示例

public partial class Form1 : Form
{
    // 类级别的字段,全局唯一,仅初始化一次
    private List<string> myPoints = new List<string>();

    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        string currentPoint = $"{e.X} , {e.Y}";
        textBox3.Text = currentPoint;
        myPoints.Add(currentPoint);
    }
}

如果要使用List<Point>类型存储,修改方式完全一致,示例如下:

public partial class Form1 : Form
{
    private List<Point> myPoints = new List<Point>();

    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        textBox3.Text = $"{e.X} , {e.Y}";
        myPoints.Add(e.Location);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:45:03