2009-06-25 29 views
67

我想這樣做,在C#中,但我不知道如何:我C#反射:如何從字符串中獲取類的引用?

有一個類名 - 例如,一個字符串:FooClass,我想調用(靜態)方法對這個類:

FooClass.MyMethod(); 

很顯然,我需要通過反射來找到對類的引用,但是如何?

回答

92

您將要使用的方法Type.GetType

這是一個很簡單的例子:

using System; 
using System.Reflection; 

class Program 
{ 
    static void Main() 
    { 
     Type t = Type.GetType("Foo"); 
     MethodInfo method 
      = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public); 

     method.Invoke(null, null); 
    } 
} 

class Foo 
{ 
    public static void Bar() 
    { 
     Console.WriteLine("Bar"); 
    } 
} 

我說簡單因爲它很容易找到一個類型這種方式是內部的同一個程序集。請參閱Jon's answer以獲得更全面的解釋,瞭解您需要了解的內容。一旦你已經檢索了這個類型,我的例子就會告訴你如何調用這個方法。

3

通過Type.GetType您可以獲取類型信息。您可以使用此類來獲取get the method信息,然後使用invoke方法(對於靜態方法,請將第一個參數留空)。

您可能還需要Assembly name才能正確識別類型。

如果類型是在當前 執行的程序集或在mscorlib.dll, 它足以提供由其命名空間合格 類型名稱。

73

您可以使用Type.GetType(string),但你需要知道類的名稱,包括命名空間,如果不是在當前彙編或MSCORLIB你需要的組件名稱來代替。 (理想情況下,使用Assembly.GetType(typeName)代替 - 我發現更容易地讓裝配基準權的條款!)

例如:

// "I know String is in the same assembly as Int32..." 
Type stringType = typeof(int).Assembly.GetType("System.String"); 

// "It's in the current assembly" 
Type myType = Type.GetType("MyNamespace.MyType"); 

// "It's in System.Windows.Forms.dll..." 
Type formType = Type.GetType ("System.Windows.Forms.Form, " + 
    "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " + 
    "PublicKeyToken=b77a5c561934e089"); 
+1

+1很好 - 我已經添加了一個答案,顯示*如何*使用類型,一旦你已經檢索到它。如果您想要,請繼續並將我的示例合併到您的答案中,然後刪除我的答案。 – 2009-06-25 15:14:03

+0

考慮到你已經被接受,我建議我們反過來 - 你把我的內容添加到你的答案,我會刪除這一個:) – 2009-06-25 15:52:49

4

有點晚了答覆,但這個應該做的伎倆

Type myType = Type.GetType("AssemblyQualifiedName"); 

您的裝配合格的名稱應該是這樣的

"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd" 
4

一個簡單的使用方法:

Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName"); 

樣品:

Type dogClass = Type.GetType("Animals.Dog, Animals"); 
相關問題