.net 返回与名称关联的对象
我正在将我的程序连接到一些外部代码。我正在设置它,以便外部代码可以实例对象,我遇到了一个问题。我在这里创建了这个函数:.net 返回与名称关联的对象,.net,vb.net,activator,createinstance,.net,Vb.net,Activator,Createinstance,我正在将我的程序连接到一些外部代码。我正在设置它,以便外部代码可以实例对象,我遇到了一个问题。我在这里创建了这个函数: Public Function InstanceOf(ByVal typename As String) As Object Dim theType As Type = Type.GetType(typename) If theType IsNot Nothing Then Return Activator.CreateInstance(theT
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响应都被接受:)仔细阅读,特别是这一部分:
如果typeName包含名称空间,但不包含程序集名称,则此方法仅按该顺序搜索调用对象的程序集和Mscorlib.dll。如果typeName使用部分或完整程序集名称完全限定,则此方法将在指定程序集中搜索。如果程序集具有强名称,则需要完整的程序集名称
由于位于System.dll(不是Mscorlib.dll)中,因此需要使用完全限定名。假设您使用的是.Net 4.0,那么:
System.Diagnostics.Process,系统,版本=4.0.0.0,区域性=中性,PublicKeyToken=b77a5c561934e089
如果不想使用完全限定名,可以遍历所有加载的程序集,并尝试使用
Assembly.GetType()
获取类型。您可以使用类似的方法来创建对象
我定义了一个本地类,还使用了您的流程示例
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
如何确定所有内容的完全限定名称?(即,您是如何获得该名称的?)如果您可以访问该类型,则类似于
typeof(Process).AssemblyQualifiedName
的内容将返回该名称。