2012-02-03 85 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