将UserControl转换为特定类型的用户控件

时间:2008-10-22 18:58:51

标签: c# asp.net user-controls

有没有办法将用户控件转换为特定的用户控件,以便我可以访问它的公共属性?基本上我正在通过占位符的控件集合进行预告,并且我正在尝试访问用户控件的公共属性。

foreach(UserControl uc in plhMediaBuys.Controls)
{
    uc.PulblicPropertyIWantAccessTo;
}

3 个答案:

答案 0 :(得分:8)

foreach(UserControl uc in plhMediaBuys.Controls) {
    MyControl c = uc as MyControl;
    if (c != null) {
        c.PublicPropertyIWantAccessTo;
    }
}

答案 1 :(得分:4)

foreach(UserControl uc in plhMediaBuys.Controls)
{
  if (uc is MySpecificType)
  {
    return (uc as MySpecificType).PulblicPropertyIWantAccessTo;
  }
}

答案 2 :(得分:2)

铸造

我更喜欢使用:

foreach(UserControl uc in plhMediaBuys.Controls)
{
    ParticularUCType myControl = uc as ParticularUCType;
    if (myControl != null)
    {
        // do stuff with myControl.PulblicPropertyIWantAccessTo;
    }
}

主要是因为使用is关键字导致两个(准昂贵的)强制转换:

if( uc is ParticularUCType ) // one cast to test if it is the type
{
    ParticularUCType myControl = (ParticularUCType)uc; // second cast
    ParticularUCType myControl = uc as ParticularUCType; // same deal this way
    // do stuff with myControl.PulblicPropertyIWantAccessTo;
}

参考