C#reflection:如何从string获取类的引用?

我想在C#中做到这一点,但我不知道如何:

我有一个类名为-eg: FooClass的string,我想在这个类上调用(静态)方法:

 FooClass.MyMethod(); 

很显然,我需要通过反思来find这个类的引用,但是如何呢?

您将要使用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"); } } 

我说简单,因为很容易find这种types的内部相同的组件。 请参阅Jon的回答,以获得更详细的解释,了解您需要了解的内容。 一旦你已经检索到types,我的例子显示如何调用该方法。

你可以使用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"); 

有点迟到的答复,但这应该做的伎俩

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

你的程序集限定名应该是这样的

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

简单的用法:

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

样品:

 Type dogClass = Type.GetType("Animals.Dog, Animals"); 

通过Type.GetType你可以得到types信息。 您可以使用此类获取方法信息,然后调用方法(对于静态方法,请将第一个参数留空)。

您可能还需要程序集名称来正确标识types。

如果types位于当前正在执行的程序集或Mscorlib.dll中,则只需提供由其名称空间限定的types名就足够了。