0

プログラムを外部コードに接続しています。外部コードがオブジェクトをインスタンス化できるように設定していますが、問題が発生しました。ここでこの関数を作成しました:

Public Function InstanceOf(ByVal typename As String) As Object
    Dim theType As Type = Type.GetType(typename)
    If theType IsNot Nothing Then
        Return Activator.CreateInstance(theType)
    End If
    Return Nothing
End Function

オブジェクトを作成しようとしていSystem.Diagnostics.Processます。Nothingただし、何らかの理由で、オブジェクトの代わりに常に返されます。私が間違っていることを誰かが知っていますか?

私はVB.netでこれを行っているので、すべての.net応答が受け入れられます:)

4

2 に答える 2

1

オブジェクトの作成には、このようなものを使用できます。

ローカルクラスを定義し、プロセス例も使用しました。

Public Class Entry
    Public Shared Sub Main()
        Dim theName As String
        Dim t As Type = GetType(AppleTree)
        theName = t.FullName
        Setup.InstanceOf(theName)

        t = GetType(Process)

        theName = t.FullName & ", " & GetType(Process).Assembly.FullName


        Setup.InstanceOf(theName)

    End Sub
End Class


Public Class Setup
    Shared function InstanceOf(typename As String) as object 
        Debug.Print(typename)
        Dim theType As Type = Type.GetType(typename)
        If theType IsNot Nothing Then
            Dim o As Object = Activator.CreateInstance(theType)
            '
            Debug.Print(o.GetType.ToString)
            return o
        End If
        return nothing 
    End function
End Class

Public Class AppleTree
    Public Sub New()
        Debug.Print("Apple Tree Created")
    End Sub
End Class
于 2012-02-03T01:36:13.727 に答える
1

特に、この部分のドキュメントType.GetType()を注意深く読んでください。

typeNameに名前空間が含まれているがアセンブリ名は含まれていない場合、このメソッドは呼び出し元のオブジェクトのアセンブリとMscorlib.dllのみをこの順序で検索します。typeNameが部分的または完全なアセンブリ名で完全に修飾されている場合、このメソッドは指定されたアセンブリを検索します。アセンブリに厳密な名前がある場合は、完全なアセンブリ名が必要です。

はSystem.dll(Mscorlib.dllではない)にあるためSystem.Diagnostics.Process、完全修飾名を使用する必要があります。.Net 4.0を使用しているとすると、次のようになります。

System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

完全修飾名を使用したくない場合は、ロードされたすべてのアセンブリを調べて、を使用して型を取得してみてくださいAssembly.GetType()

于 2012-02-03T01:22:14.493 に答える