WinForm (System.Windows.Forms.Control) 與 WebForm (System.Web.UI.Control) 無共同基類,無法直接編寫通用邏輯操作控件屬性(ID、值、子控件)。
// 統一訪問接口
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
}
}
txt+屬性名)與反射綁定思路。ControlHelper 實現獲取/設置/驗證。