0

ライブラリにユーザー コントロールがあり、それを継承して更新する必要があります。私が今抱えている問題は、新しいユーザー コントロールを直接インスタンス化できないことです。ユーザー コントロールのインスタンスを作成して渡すライブラリ内のメソッドを呼び出す必要があります。以下のサンプルコードを確認してください。

キャストを使用しようとしましたが、InvalidCastException が発生しました。これは、2 番目が 1 番目よりも多くのストレージを必要とするためだと思います。

これを手伝ってくれてありがとう。

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
4

1 に答える 1

0

これは、ExtendedCustomControl をインスタンス化していないためです。CustomControl をインスタンス化しています。Activator.CreateObject は基本クラスを作成しているだけです。実際にキャスト先のクラスでない限り、何かをアップキャストすることはできません。

CreateCustomControl() で System.Type を受け取り、それを代わりに Activator.CreateInstance に渡したいと思うかもしれません。そうすれば、あなたが望むものを作ることができるかもしれませんか?

于 2009-07-21T02:24:29.470 に答える