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

仔细阅读文档Type.GetType(),特别是这部分:

如果typeName包含命名空间但不包含程序集名称,则此方法仅按此顺序搜索调用对象的程序集和 Mscorlib.dll。如果typeName是完全限定的部分或完整程序集名称,则此方法在指定的程序集中进行搜索。如果程序集具有强名称,则需要完整的程序集名称。

由于System.Diagnostics.Process位于 System.dll(不是 Mscorlib.dll)中,因此您需要使用完全限定名称。假设您使用的是 .Net 4.0,那就是:

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

如果您不想使用完全限定名称,您可以浏览所有加载的程序集并尝试使用Assembly.GetType().

于 2012-02-03T01:22:14.493 回答
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 回答