.net 继承自定义控件时出现问题
我的库中有一个用户控件,我需要继承它并对其进行一些更新。我现在面临的问题是,我无法直接实例化新的用户控件。我必须调用库中的一个方法,该方法将创建并传递用户控件的实例。请检查下面的示例代码 我试图使用铸造,但我得到了无效的铸造例外。我想那是因为第二个比第一个需要更多的存储空间 提前感谢您在这方面的帮助.net 继承自定义控件时出现问题,.net,vb.net,inheritance,visual-inheritance,.net,Vb.net,Inheritance,Visual Inheritance,我的库中有一个用户控件,我需要继承它并对其进行一些更新。我现在面临的问题是,我无法直接实例化新的用户控件。我必须调用库中的一个方法,该方法将创建并传递用户控件的实例。请检查下面的示例代码 我试图使用铸造,但我得到了无效的铸造例外。我想那是因为第二个比第一个需要更多的存储空间 提前感谢您在这方面的帮助 Namespace ProjectA.Components Public Class MainClass Public Function CreateCustomCont
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
这是因为您不是在实例化ExtendedCustomControl,而是在实例化CustomControl。Activator.CreateObject正在创建基类。你不能向上投射某些东西,除非它确实属于你要投射的类别 也许您希望CreateCustomControl()接受System.Type,然后将其传递到Activator.CreateInstance?这样你就可以做你想要的了