首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 雙向鏈結清單模擬瀏覽器前進/後退功能 (三) - 使用者介面整合

     編輯:關於C語言

承接前兩篇資料結構與核心邏輯,本文展示如何在 WinForms/WebForms 頁面中整合 HistoryManager (基於 LinkedList<T>) 實現前進/後退按鈕狀態同步與頁面載入。

頁面端整合程式碼

public partial class BrowserForm : Form
{
    private readonly HistoryManager _history = new HistoryManager();

    private void AddHistory(string title, string html, string url)
    {
        _history.Add(new HistoryItem { Title = title, Html = html, Url = url });
        UpdateNavButtons();
    }

    private void BtnBack_Click(object sender, EventArgs e)
    {
        _history.Back();
        LoadCurrentPage();
        UpdateNavButtons();
    }

    private void BtnForward_Click(object sender, EventArgs e)
    {
        _history.Forward();
        LoadCurrentPage();
        UpdateNavButtons();
    }

    private void LoadCurrentPage()
    {
        var item = _history.Current;
        if (item != null)
        {
            webBrowser.DocumentText = item.Html;
            txtUrl.Text = item.Url;
            Text = item.Title;
        }
    }

    private void UpdateNavButtons()
    {
        btnBack.Enabled = _history.CanBack;
        btnForward.Enabled = _history.CanForward;
    }
}

HistoryManager 核心實作回顧

public class HistoryManager
{
    private readonly LinkedList _list = new LinkedList();
    private LinkedListNode _current;

    public HistoryItem Current => _current?.Value;
    public bool CanBack => _current?.Previous != null;
    public bool CanForward => _current?.Next != null;

    public void Add(HistoryItem item)
    {
        if (_current != null)
        {
            // 移除前進歷史 (C, D 被捨棄)
            while (_current.Next != null)
                _list.RemoveLast();
        }
        _current = _list.AddLast(item);
    }

    public void Back() => _current = _current?.Previous;
    public void Forward() => _current = _current?.Next;
}

關鍵行為驗證 (符合 IE/Chrome 邏輯)

操作序列歷史清單狀態當前位置
造訪 A → B → C → DA - B - C - DD
後退到 BA - B - C - DB
造訪 EA - B - E (C, D 移除)E

LinkedList<T> 的 O(1) 節點插入/刪除/前後導航特性,完美契合瀏覽器歷史需求。實務中尚需處理:快取策略、序列化持久化、多索引標籤隔離、前進/後退手勢支援等。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved