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

C# Control 類別強制轉型為具體伺服器控制項型別

     編輯:關於C#

情境

遍歷 Control.Controls 集合時,取得的是基類 Control 參考,需轉型為具體型別 (TextBox, Button, Panel 等) 以存取特有屬性/方法。

型別檢查與轉型方式比較

方式程式碼優點缺點
is 型別模式 (C# 7+)if (ctrl is TextBox tb) tb.Text = "";**最簡潔、安全**、合併檢查與轉型需 C# 7+
as 操作符 + null 檢查var tb = ctrl as TextBox; if (tb != null) tb.Text = "";不拋例外、可分離檢查轉型較冗長
GetType() 比較if (ctrl.GetType() == typeof(TextBox))精確型別匹配 (不含繼承)不支援繼承、字串比較易錯
is 關鍵字 (舊版)if (ctrl is TextBox) { var tb = (TextBox)ctrl; }支援繼承關係需二次轉型
字串比較 (不推薦)ctrl.GetType().ToString() == "System.Web.UI.WebControls.TextBox"—脆弱、效能差、命名空間變更即失效

完整遍歷範例 (WinForms / ASP.NET WebForms 通用)


private void ClearAllTextBoxes(Control parent)
{
    foreach (Control ctrl in parent.Controls)
    {
        // 遞迴處理巢狀容器
        if (ctrl.HasChildren) ClearAllTextBoxes(ctrl);

        // 型別模式匹配 (推薦)
        if (ctrl is TextBox tb)
        {
            tb.Clear();
        }
        else if (ctrl is CheckBox cb)
        {
            cb.Checked = false;
        }
        else if (ctrl is RadioButton rb)
        {
            rb.Checked = false;
        }
        else if (ctrl is ComboBox cmb)
        {
            cmb.SelectedIndex = -1;
        }
        // Panel 等容器無需特殊處理,遞迴已涵蓋
    }
}

// 使用
ClearAllTextBoxes(this); // 表單或容器

ASP.NET WebForms 特有:FindControl 遞迴查找


public Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id) return root;
    foreach (Control ctrl in root.Controls)
    {
        var found = FindControlRecursive(ctrl, id);
        if (found != null) return found;
    }
    return null;
}

// 使用
var txt = FindControlRecursive(this, "txtUserName") as TextBox;
txt?.Text = "Default";

效能提示

  • is / as 為 IL 指令 isinst,**極快** (奈秒級),無效能顧慮。
  • 避免 GetType().ToString() 字串比較 (配置字串、字串比較、不支援繼承)。
  • 大量控制項樹遍歷時,考慮快取 typeof(TextBox) 等 Type 物件 (雖 typeof 編譯期常數已極快)。

現代模式:Visitor / 型別開關 (C# 8 Switch Expression)


private void ProcessControl(Control ctrl) => ctrl switch
{
    TextBox tb => tb.Clear(),
    CheckBox cb => cb.Checked = false,
    RadioButton rb => rb.Checked = false,
    ComboBox cmb => cmb.SelectedIndex = -1,
    { HasChildren: true } container => 
        foreach (Control child in container.Controls) ProcessControl(child),
    _ => { } // 忽略其他型別
};

掌握 is 型別模式與遞迴遍歷,即能安全、高效處理控制項樹中的型別轉換需求。

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