无法在winforms控件中定位新的子类属性



多亏了这里的帮助,我已经设法递归地循环通过我的winform上的所有控件,并找到我的子类控件,但当我试图更新我的用户定义的属性_key和_value对象ctrl不暴露他们:(我使用下面的ctrlContainer是作为

传递的调用表单
foreach (Control ctrl in ctrlContainer.Controls)
{
    // code to find my specific sub classed textBox
    // found my control
    // now update my new property _key
    ctrl._key does not exist :(
    I know the ctrl exists and is valid because ctrl.Text = "I've just added this text" works.
    _key is visible when looking at the control in the form designer.
}
谁能给我一个提示,我做错了什么?谢谢。

_key不存在,因为您正在查看Control

try doing:

foreach (var ctrl in ctrlContainer.Controls.OfType<MyControl>())
{
     ctrl._key = "somthing";
}

这是因为您的参考类型为Control (foreach (Control ctrl),我假设这不是您的子类控制。该引用只理解属于它的成员,_key可能属于派生类。试试这个:

foreach (Control ctrl in ctrlContainer.Controls)
{
    // code to find my specific sub classed textBox
    // found my control
    // now update my new property _key
    if (ctrl is MyControl)
    {
        MyControl myControl = (MyControl)ctrl;
        myControl._key = "";
    }
}

或者您可以更改迭代器以只查找控件的实例,正如Sebastian所建议的那样。这样代码会更简洁。

最新更新