using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LB_SmartVision.Forms.Pages { // 最优方案实现 public class ControlStateManager { private readonly Dictionary _controlMap = new Dictionary(); private readonly TableLayoutPanel _tablePanel; public ControlStateManager(TableLayoutPanel tablePanel) { _tablePanel = tablePanel; BuildControlMap(); } // 初始化时构建控件字典(只需一次) private void BuildControlMap(Control parent = null) { parent = parent ?? _tablePanel; foreach (Control control in parent.Controls) { if (!string.IsNullOrEmpty(control.Name)) { _controlMap[control.Name] = control; } if (control.HasChildren) { BuildControlMap(control); } } } // O(1) 快速访问 public T GetControl(string name) where T : Control { return _controlMap.TryGetValue(name, out Control control) ? control as T : null; } // 获取TextBox值 public string GetTextBoxValue(string name) { return GetControl(name)?.Text; } // 获取CheckBox状态 public bool? GetCheckBoxState(string name) { return GetControl(name)?.Checked; } /// /// 获取 ComboBox 的选中项文本 /// public string GetComboBoxText(string comboBoxName) { var comboBox = GetControl(comboBoxName); return comboBox?.SelectedItem?.ToString() ?? string.Empty; } /// /// 获取 ComboBox 的选中索引 /// public int GetComboBoxSelectedIndex(string comboBoxName) { var comboBox = GetControl(comboBoxName); return comboBox?.SelectedIndex ?? -1; } /// /// 获取 ComboBox 的所有项 /// public List GetComboBoxItems(string comboBoxName) { var comboBox = GetControl(comboBoxName); return comboBox?.Items.Cast().ToList() ?? new List(); } /// /// 获取 ComboBox 的完整状态 /// public ComboBoxState GetComboBoxState(string comboBoxName) { var comboBox = GetControl(comboBoxName); if (comboBox == null) return null; return new ComboBoxState { Items = comboBox.Items.Cast().ToList(), SelectedIndex = comboBox.SelectedIndex, SelectedItem = comboBox.SelectedItem, Text = comboBox.Text }; } // 动态更新控件映射(当添加/删除控件时调用) public void RefreshControlMap() { _controlMap.Clear(); BuildControlMap(); } } // ComboBox 状态数据结构 public class ComboBoxState { public List Items { get; set; } public int SelectedIndex { get; set; } public object SelectedItem { get; set; } public string Text { get; set; } } }