我想在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)
小智 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)
回复的时间有点晚,但这应该可以解决问题
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)