2009-03-03 49 views
6

在.NET中將字符串轉換爲Type對象的最佳方式是什麼?從.NET中的字符串獲取Type對象的最佳方式

要考慮的問題:

  • 的類型可以是在一個不同的組件。
  • 該類型的程序集可能尚未加載。

這是我的嘗試,但它並沒有解決第二個問題

Public Function FindType(ByVal name As String) As Type 
    Dim base As Type 

    base = Reflection.Assembly.GetEntryAssembly.GetType(name, False, True) 
    If base IsNot Nothing Then Return base 

    base = Reflection.Assembly.GetExecutingAssembly.GetType(name, False, True) 
    If base IsNot Nothing Then Return base 

    For Each assembly As Reflection.Assembly In _ 
     AppDomain.CurrentDomain.GetAssemblies 
     base = assembly.GetType(name, False, True) 
     If base IsNot Nothing Then Return base 
    Next 
    Return Nothing 
End Function 
+0

解決第二種情況很困難。一般如何知道卸載的組件所在的位置?否則看到[這個答案](http://stackoverflow.com/a/7286354/661933),相當不錯。 – nawfal 2013-12-05 19:44:48

回答

3

您可能需要爲第二個方法調用GetReferencedAssemblies()方法。

namespace reflectme 
{ 
    using System; 
    public class hello 
    { 
     public hello() 
     { 
      Console.WriteLine("hello"); 
      Console.ReadLine(); 
     } 
     static void Main(string[] args) 
     { 
      Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType("reflectme.hello"); 
      t.GetConstructor(System.Type.EmptyTypes).Invoke(null); 
     } 
    } 
} 
9

您可以爲了做到這一點使用Type.GetType(string)。類型名稱必須是組件限定的,但該方法將根據需要加載組件。如果類型位於mscorlid或執行GetType調用的程序集中,則不需要程序集限定條件。

+0

請注意,如果未找到類型,則不會引發異常,它將返回null。如果您希望類型存在,那麼使用Type.GetType(string,bool)重載並傳遞true將是值得的,如果類型不能被載入,則會拋出該錯誤。 – 2009-03-03 21:50:28

相關問題