2012-02-03 105 views
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回应被接受:)

回答

1

通过the documentation of 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()类型。

+0

如何确定一切的完全限定名? (即你是怎么想出这个名字的?) – FreeSnow 2012-02-03 01:31:17

+1

如果你可以访问这个类型,那么'typeof(Process).AssemblyQualifiedName'就会返回它。 – svick 2012-02-03 01:48:02

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