C# 将UserControl强制转换为特定类型的用户控件

C# 将UserControl强制转换为特定类型的用户控件,c#,asp.net,user-controls,C#,Asp.net,User Controls,有没有办法将用户控件强制转换为特定的用户控件,以便我可以访问它的公共属性?基本上,我正在浏览占位符的控件集合,并尝试访问用户控件的公共属性 foreach(UserControl uc in plhMediaBuys.Controls) { uc.PulblicPropertyIWantAccessTo; } 铸造 我更喜欢使用: foreach(UserControl uc in plhMediaBuys.Controls) { ParticularUCType myCont

有没有办法将用户控件强制转换为特定的用户控件,以便我可以访问它的公共属性?基本上,我正在浏览占位符的控件集合,并尝试访问用户控件的公共属性

foreach(UserControl uc in plhMediaBuys.Controls)
{
    uc.PulblicPropertyIWantAccessTo;
}
铸造 我更喜欢使用:

foreach(UserControl uc in plhMediaBuys.Controls)
{
    ParticularUCType myControl = uc as ParticularUCType;
    if (myControl != null)
    {
        // do stuff with myControl.PulblicPropertyIWantAccessTo;
    }
}
主要是因为使用is关键字会导致两次(准昂贵)强制转换:

工具书类

虽然fallen888也可以使用,但我更喜欢这种方法。事实上,这个示例对我来说效率较低,因为您正在创建另一个MyControl实例。这段代码实际上并没有创建MyControl的新实例,它只是创建了一个新的引用。引用本质上是指针,所以这里不应该有性能损失。事实上,如果您使用“as”关键字或只是强制转换变量,您也在做同样的事情。两者之间的唯一区别是,如果“as”不能强制转换,它将返回null,而不是引发异常。我认为这是正确的,但它似乎仍然没有必要-这增加了代码的复杂性。实际上,如果使用“as”关键字或仅强制转换变量,您也在做同样的事情。两者之间的唯一区别是,如果“as”不能强制转换,它将返回null,而不是抛出异常。这是真的,但如果它不能强制转换,它将永远不会到达该行。
foreach(UserControl uc in plhMediaBuys.Controls) {
    MyControl c = uc as MyControl;
    if (c != null) {
        c.PublicPropertyIWantAccessTo;
    }
}
foreach(UserControl uc in plhMediaBuys.Controls)
{
    ParticularUCType myControl = uc as ParticularUCType;
    if (myControl != null)
    {
        // do stuff with myControl.PulblicPropertyIWantAccessTo;
    }
}
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;
}