C#反射:如何从字符串获取类引用?
我想用C#来做这件事,但我不知道怎么做: 我有一个带有类名的字符串,例如:C#反射:如何从字符串获取类引用?,c#,reflection,C#,Reflection,我想用C#来做这件事,但我不知道怎么做: 我有一个带有类名的字符串,例如:FooClass,我想在这个类上调用一个(静态)方法: FooClass.MyMethod(); 显然,我需要通过反射找到对该类的引用,但是如何?通过您可以获得类型信息。您可以使用这个类来定义信息,然后是方法(对于静态方法,将第一个参数保留为null) 您可能还需要正确标识类型 如果类型在当前 正在Mscorlib.dll中执行程序集或, 这就足以提供该类型 名称由其命名空间限定 您可以使用,但需要知道包括命名空间在内的
FooClass
,我想在这个类上调用一个(静态)方法:
FooClass.MyMethod();
显然,我需要通过反射找到对该类的引用,但是如何?通过您可以获得类型信息。您可以使用这个类来定义信息,然后是方法(对于静态方法,将第一个参数保留为null)
您可能还需要正确标识类型
如果类型在当前
正在Mscorlib.dll中执行程序集或,
这就足以提供该类型
名称由其命名空间限定
您可以使用,但需要知道包括命名空间在内的完整类名,如果它不在当前程序集或mscorlib中,则需要程序集名称。(理想情况下,改为使用-我发现这更容易获得正确的程序集引用!)
例如:
// "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");
您将希望使用该方法
下面是一个非常简单的例子:
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");
}
}
我说简单是因为用这种方式很容易找到同一程序集内部的类型。关于你需要了解的内容,请参阅更详细的解释。一旦您检索到该类型,我的示例将向您展示如何调用该方法。回复有点晚,但这应该可以做到
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()
获取类名,还可以使用Activator.CreateInstance(type)创建它的对象代码>
+1做得很好-我添加了一个答案,说明了在检索该类型后如何使用它。如果您愿意,请继续并将我的示例合并到您的答案中,我将删除我的示例。鉴于您的示例已被接受,我建议我们以另一种方式执行-您将我的内容添加到您的答案中,我将删除此内容:)只是为了进一步扩展您的答案,如果您不确定将什么作为文本传递给GetType函数,并且您可以访问该类,那么请查看typeof(class).AssemblyQualifiedName,这将给出清晰的想法。感谢您明确说明程序集限定名应该是什么样子。
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; }
}
}