【发布时间】:2010-11-05 21:05:28
【问题描述】:
我想在 C# 中执行此操作,但我不知道如何:
我有一个带有类名的字符串-例如:FooClass,我想在这个类上调用一个(静态)方法:
FooClass.MyMethod();
显然,我需要通过反射找到对类的引用,但是如何?
【问题讨论】:
标签: c# reflection
我想在 C# 中执行此操作,但我不知道如何:
我有一个带有类名的字符串-例如:FooClass,我想在这个类上调用一个(静态)方法:
FooClass.MyMethod();
显然,我需要通过反射找到对类的引用,但是如何?
【问题讨论】:
标签: c# reflection
您将需要使用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(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 typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");
示例:
Type dogClass = Type.GetType("Animals.Dog, Animals");
【讨论】:
回复有点晚了,但这应该可以解决问题
Type myType = Type.GetType("AssemblyQualifiedName");
你的程序集限定名称应该是这样的
"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"
【讨论】:
通过Type.GetType可以获取类型信息。你可以使用这个类来get the method信息然后invoke方法(对于静态方法,保留第一个参数为空)。
您可能还需要Assembly name 才能正确识别类型。
如果类型在当前 执行程序集或在 Mscorlib.dll 中, 提供类型就足够了 名称由其命名空间限定。
【讨论】:
我们可以使用
Type.GetType()
获取类名,也可以使用Activator.CreateInstance(type);创建它的对象
using System;
using System.Reflection;
namespace MyApplication
{
class Application
{
static void Main()
{
Type type = Type.GetType("MyApplication.Action");
if (type == null)
{
throw new Exception("Type not found.");
}
var instance = Activator.CreateInstance(type);
//or
var newClass = System.Reflection.Assembly.GetAssembly(type).CreateInstance("MyApplication.Action");
}
}
public class Action
{
public string key { get; set; }
public string Value { get; set; }
}
}
【讨论】: