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

C# 統一獲取設置 UI 控件值(二):統一 WinForm/WebForm 控件訪問接口

     編輯:關於C語言

問題

WinForm (System.Windows.Forms.Control) 與 WebForm (System.Web.UI.Control) 無共同基類,無法直接編寫通用邏輯操作控件屬性(ID、值、子控件)。

解決方案:定義 IControl 接口 + 結構體適配器


// 統一訪問接口
interface IControl
{
    object RealControl { get; }           // 真實控件對象
    string GetControlID();                // 獲取 ID/Name
    IEnumerable GetSubControls(); // 遞歸獲取子控件
}

// WinForm 適配器
struct WinControl : IControl
{
    private readonly Control _ctl;
    public WinControl(Control ctl) => _ctl = ctl;
    public object RealControl => _ctl;
    public string GetControlID() => _ctl.Name;
    public IEnumerable GetSubControls()
    {
        foreach (Control c in _ctl.Controls) yield return new WinControl(c);
    }
}

// WebForm 適配器
struct WebControl : IControl
{
    private readonly System.Web.UI.Control _ctl;
    public WebControl(System.Web.UI.Control ctl) => _ctl = ctl;
    public object RealControl => _ctl;
    public string GetControlID() => _ctl.ID;
    public IEnumerable GetSubControls()
    {
        foreach (System.Web.UI.Control c in _ctl.Controls) yield return new WebControl(c);
    }
}

命名空間別名簡化代碼


using WinForms = System.Windows.Forms;
using WebCtl = System.Web.UI.Control;
using WinCtl = System.Windows.Forms.Control;

後續使用

通用邏輯僅依賴 IControl:


void BindEntity(object entity, IControl root)
{
    foreach (var ctrl in root.GetSubControls())
    {
        string propName = ParseControlID(ctrl.GetControlID(), GetControlType(ctrl.RealControl));
        // 反射設置 entity 的 propName
    }
}

設計要點

  • 結構體而非類:輕量、值語義、無堆分配,適配器開銷極小。
  • yield return:惰性遍歷子控件樹,內存友好。
  • 接口隔離:上層邏輯零依賴具體 UI 框架,易於單元測試與跨平台遷移。

系列脈絡

  1. 約定命名規則(txt+屬性名)與反射綁定思路。
  2. 本文:統一訪問接口與適配器模式。
  3. 通用輔助類 ControlHelper 實現獲取/設置/驗證。
  4. Controller 模式落地業務邏輯解耦。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved