访问未知类型的特定属性

时间:2011-01-26 20:25:00

标签: c# .net winforms controls textbox

我希望测试表单上的所有控件,如果给定的控件是TextBox,我想记录该控件的MaxLength属性。我可以像这样测试每个控件:

        foreach (Control ctrl in this.Controls)
        {
            if (ctrl is TextBox)
            {
                // Get the MaxLength property.
            }
        }

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

3 个答案:

答案 0 :(得分:6)

您需要将ctrl投射到TextBox

TextBox textBox = ctrl as TextBox;
if (textBox != null) {
    ...
}

as operator将尝试将其操作数强制转换为指定的类型,如果操作数的类型不同,则返回null

This pattern is faster than checking is, then casting separately

答案 1 :(得分:1)

foreach (Control ctrl in this.Controls)
{
    if (ctrl is TextBox)
    {
        var result = ((TextBox)ctrl).MaxLength;
    }
}

答案 2 :(得分:1)

正如SLaks所说,你需要以某种方式施展。您可能想要使用as operator

foreach (Control ctrl in this.Controls)
{
    TextBox tb = ctrl as TextBox;
    if (tb != null)
    {
        int max = tb.MaxLength;
        // ...
    }
}

如果您没有使用非文本框控件执行任何其他操作,您可能需要考虑使用LINQ:

foreach (TextBox tb in this.Controls.OfType<TextBox>())
{
    int max = tb.MaxLength;
    // ...
}