C# 将 UserControl 转换为特定类型的用户控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/227121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting a UserControl as a specific type of user control
提问by angelo
Is there a way to cast a user control as a specific user control so I have access to it's public properties? Basicly I'm foreaching through a placeholder's controls collection and I'm trying to access the user control's public properties.
有没有办法将用户控件转换为特定的用户控件,以便我可以访问它的公共属性?基本上,我正在通过占位符的控件集合进行搜索,并且我正在尝试访问用户控件的公共属性。
foreach(UserControl uc in plhMediaBuys.Controls)
{
uc.PulblicPropertyIWantAccessTo;
}
采纳答案by Chris Pietschmann
foreach(UserControl uc in plhMediaBuys.Controls) {
MyControl c = uc as MyControl;
if (c != null) {
c.PublicPropertyIWantAccessTo;
}
}
回答by Kon
foreach(UserControl uc in plhMediaBuys.Controls)
{
if (uc is MySpecificType)
{
return (uc as MySpecificType).PulblicPropertyIWantAccessTo;
}
}
回答by wprl
Casting
铸件
I prefer to use:
我更喜欢使用:
foreach(UserControl uc in plhMediaBuys.Controls)
{
ParticularUCType myControl = uc as ParticularUCType;
if (myControl != null)
{
// do stuff with myControl.PulblicPropertyIWantAccessTo;
}
}
Mainly because using the is keyword causes two (quasi-expensive) casts:
主要是因为使用 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;
}