将UserControl强制转换为特定类型的用户控件
本文关键字:类型 用户 控件 UserControl 转换 | 更新日期: 2023-09-27 17:48:51
有没有办法将用户控件强制转换为特定的用户控件,这样我就可以访问它的公共属性?基本上,我正在遍历占位符的控件集合,并尝试访问用户控件的公共属性。
foreach(UserControl uc in plhMediaBuys.Controls)
{
uc.PulblicPropertyIWantAccessTo;
}
foreach(UserControl uc in plhMediaBuys.Controls) {
MyControl c = uc as MyControl;
if (c != null) {
c.PublicPropertyIWantAccessTo;
}
}
foreach(UserControl uc in plhMediaBuys.Controls)
{
if (uc is MySpecificType)
{
return (uc as MySpecificType).PulblicPropertyIWantAccessTo;
}
}
铸造
我更喜欢使用:
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;
}
参考文献
- C中的3个Cast算子#
- C中类型铸造对执行性能的影响#