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

如何在图像编辑App中用List实现撤销重做并解决索引越界问题

图像处理App撤销/重做功能索引越界问题修复方案

原代码问题分析

  • 撤销逻辑错误:当indexer为0时,执行indexer -=1会得到-1,后续直接访问Queue.ElementAt(indexer)会触发索引越界(列表最小有效索引为0)
  • 重做逻辑错误:判断条件indexer > Queue.Count完全不符合列表索引规则(最大有效索引是Queue.Count-1),且缺少更新UI的代码,导致即使索引正确也不会刷新图像

修正后的代码实现

撤销操作事件处理器

case Resource.Id.action_do:
    if(Queue.Count > 0){
        // 先递减索引,再限制最小值为0,避免越界
        indexer -= 1;
        if(indexer < 0){
            indexer = 0;
        }
        // 也可以用更简洁的写法:indexer = Math.Max(indexer - 1, 0);
        var bmp = Queue.ElementAt(indexer);
        pictureBox1.SetImageBitmap(bmp); 
    }
break;

重做操作事件处理器

case Resource.Id.action_redo:
    if(Queue.Count > 0) {
        // 先递增索引,再限制最大值为列表最后一个元素的索引
        indexer += 1;
        if(indexer >= Queue.Count){
            indexer = Queue.Count - 1;
        }
        // 也可以用更简洁的写法:indexer = Math.Min(indexer + 1, Queue.Count - 1);
        var bmp = Queue.ElementAt(indexer);
        pictureBox1.SetImageBitmap(bmp); 
    } 
break;

额外优化建议

当用户在撤销几步后执行新的图像操作,应该清除当前索引之后的所有历史记录(这些记录已经被新操作覆盖,无需保留),避免出现无效的重做项:

// 图像操作时更新列表和索引
if(indexer < Queue.Count - 1){
    // 移除当前索引之后的所有记录
    Queue.RemoveRange(indexer + 1, Queue.Count - indexer - 1);
}
Queue.Add(bitmap);
indexer = Queue.Count - 1;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:32:22