访问未知类型的特定属性

Geo*_*Ego 0 .net c# controls textbox winforms

我期待测试窗体上的所有控件,如果给定的控件是TextBox,我想记录该控件的MaxLength属性.我可以像这样测试每个控件:

        foreach (Control ctrl in this.Controls)
        {
            if (ctrl is TextBox)
            {
                // Get the MaxLength property.
            }
        }
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何获取控件的MaxLength属性,因为它特定于TextBox而不是ctrl的属性列表.

SLa*_*aks 6

你需要施放ctrlTextBox:

TextBox textBox = ctrl as TextBox;
if (textBox != null) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

as运营商将尝试它的操作数转换为指定的类型,并返回null如果操作数是不同的类型.

这种模式比检查更快is,然后单独铸造.