继承自定义控件的问题

时间:2009-07-21 02:20:49

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

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

我尝试使用强制转换,但我得到了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

1 个答案:

答案 0 :(得分:0)

这是因为您没有实例化ExtendedCustomControl,而是实例化CustomControl。 Activator.CreateObject只是创建基类。除非它实际上属于你所投入的类,否则你无法转发。

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