【问题标题】:Casting a UserControl as a specific type of user control将 UserControl 转换为特定类型的用户控件
【发布时间】:2015-12-11 01:36:20
【问题描述】:

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

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

【问题讨论】:

    标签: c# asp.net user-controls


    【解决方案1】:
    foreach(UserControl uc in plhMediaBuys.Controls) {
        MyControl c = uc as MyControl;
        if (c != null) {
            c.PublicPropertyIWantAccessTo;
        }
    }
    

    【讨论】:

    • 我更喜欢这种方式,虽然fall888也可以。
    • 事实上,这个例子对我来说似乎效率较低,因为您正在创建另一个 MyControl 实例。
    • 这段代码实际上并没有创建一个新的 MyControl 实例,它只是创建了一个新的引用。引用本质上是指针,所以这里不应该有性能损失。
    • 实际上,如果您使用“as”关键字或只是强制转换变量,您正在做同样的事情。两者的唯一区别是“as”如果不能强制转换则返回null,而不是抛出异常。
    • 我的立场是正确的,但它似乎仍然没有必要 - 增加了代码的复杂性。
    【解决方案2】:
    foreach(UserControl uc in plhMediaBuys.Controls)
    {
      if (uc is MySpecificType)
      {
        return (uc as MySpecificType).PulblicPropertyIWantAccessTo;
      }
    }
    

    【讨论】:

    • 实际上,如果您使用“as”关键字或只是强制转换变量,您正在做同样的事情。两者的唯一区别是“as”如果不能强制转换则返回null,而不是抛出异常。
    • 是的,但如果它无法投射,它将永远不会到达那条线。
    【解决方案3】:

    铸造

    我更喜欢使用:

    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;
    }
    

    参考文献

    【讨论】:

      猜你喜欢
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      相关资源
      最近更新 更多