我想这样做,在C#中,但我不知道如何:我C#反射:如何从字符串中获取类的引用?
有一个类名 - 例如,一个字符串:FooClass
,我想调用(静态)方法对这个类:
FooClass.MyMethod();
很显然,我需要通过反射来找到对类的引用,但是如何?
我想这样做,在C#中,但我不知道如何:我C#反射:如何从字符串中获取类的引用?
有一个类名 - 例如,一个字符串:FooClass
,我想调用(静态)方法对这个类:
FooClass.MyMethod();
很显然,我需要通过反射来找到对类的引用,但是如何?
您将要使用的方法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以获得更全面的解释,了解您需要了解的内容。一旦你已经检索了这个类型,我的例子就会告诉你如何调用这个方法。
通过Type.GetType您可以获取类型信息。您可以使用此类来获取get the method信息,然后使用invoke方法(对于静态方法,请将第一个参数留空)。
您可能还需要Assembly name才能正确识别类型。
如果类型是在当前 执行的程序集或在mscorlib.dll, 它足以提供由其命名空间合格 类型名称。
您可以使用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");
+1很好 - 我已经添加了一个答案,显示*如何*使用类型,一旦你已经检索到它。如果您想要,请继续并将我的示例合并到您的答案中,然后删除我的答案。 – 2009-06-25 15:14:03
考虑到你已经被接受,我建议我们反过来 - 你把我的内容添加到你的答案,我会删除这一个:) – 2009-06-25 15:52:49