2009-07-21 122 views
0

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

我试图使用转换,我得到了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 

回答

0

这是因为您没有实例化ExtendedCustomControl,所以您正在实例化一个CustomControl。 Activator.CreateObject只是创建基类。除非它真的属于你正在投入的课程,否则你不能上传任何东西。

也许你想要CreateCustomControl()采取System.Type,然后将其传递到Activator.CreateInstance,而不是?这样你可以做出你想要的东西?