2009-07-21 88 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,而不是?這樣你可以做出你想要的東西?