【问题标题】:Issue with inheriting custom control继承自定义控件的问题
【发布时间】:2009-07-21 02:20:49
【问题描述】:

我的库中有一个用户控件,我需要继承它并对其进行一些更新。我现在遇到的问题是我无法直接实例化新的用户控件。我必须调用库中的一个方法,该方法将创建并传递用户控件的一个实例。请查看下面的示例代码。

我尝试使用强制转换并得到 InvalidCastException。我认为这是因为第二个比第一个需要更多的存储空间。

在此先感谢您提供帮助。

Namespace ProjectA.Components

    Public Class MainClass

        Public Function CreateCustomControl() As CustomControl
            Dim cc As CustomControl = Activator.CreateInstance(Of CustomControl)()
            Return cc
        End Function

    End Class

    Public Class CustomControl
        Inherits System.Windows.Forms.UserControl
    End Class

End Namespace

Namespace ProjectB

    Public Class ExtendedCustomControl
        Inherits ProjectA.Components.CustomControl
    End Class

    Public Class MainForm
        Inherits System.Windows.Forms.Form

        Private Sub CreateInstance()
            Dim i As New ProjectA.Components.MainClass
            Dim myControl As ExtendedCustomControl = i.CreateCustomControl
            ' InvalidCastException is thrown.
        End Sub

    End Class

End Namespace

【问题讨论】:

    标签: .net vb.net inheritance visual-inheritance


    【解决方案1】:

    这是因为您不是在实例化 ExtendedCustomControl,而是在实例化 CustomControl。 Activator.CreateObject 只是创建基类。除非它实际上是您要转换的类,否则您不能向上转换。

    也许您希望 CreateCustomControl() 采用 System.Type,然后将其传递给 Activator.CreateInstance?这样你也许可以做出你想要的?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-09
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2011-08-01
      • 1970-01-01
      • 2011-04-08
      相关资源
      最近更新 更多