C#反思:如何从字符串中获取类引用?

rut*_*ger 82 c# reflection

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

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

FooClass.MyMethod();
Run Code Online (Sandbox Code Playgroud)

显然,我需要通过反思找到对类的引用,但是如何?

And*_*are 119

您将需要使用该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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我说简单,因为很容易找到一种类型,这是同一个程序集的内部.有关您需要了解的内容,请参阅Jon的答案,以获得更全面的解释.检索完该类型后,我的示例将向您展示如何调用该方法.


Jon*_*eet 92

您可以使用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");
Run Code Online (Sandbox Code Playgroud)

  • 只是为了进一步扩展你的答案,如果你不确定将什么作为文本传递给GetType函数,你可以访问这个类,然后查看typeof(class).AssemblyQualifiedName,这将给出清晰的想法. (4认同)
  • +1干得好 - 我添加了一个答案,显示*如何*在检索到该类型后使用该类型。如果您愿意,请继续将我的示例合并到您的答案中,我将删除我的示例。 (2认同)

小智 8

一个简单的用途:

Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");
Run Code Online (Sandbox Code Playgroud)

样品:

Type dogClass = Type.GetType("Animals.Dog, Animals");
Run Code Online (Sandbox Code Playgroud)


Atu*_*ary 6

回复的时间有点晚,但这应该可以解决问题

Type myType = Type.GetType("AssemblyQualifiedName");
Run Code Online (Sandbox Code Playgroud)

您的程序集合格名称应如下所示

"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"
Run Code Online (Sandbox Code Playgroud)

  • 感谢您明确说明程序集限定名称的外观。 (4认同)