C#反思:如何从字符串获取类引用? [英] C# Reflection: How to get class reference from string?

查看:116
本文介绍了C#反思:如何从字符串获取类引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to do this in C#, but I don't know how:

我有一个类名-e.g.字符串FooClass - 我想调用这个类(静态)方法:)FooClass.MyMethod(;

I have a string with a class name -e.g. "FooClass"- and I want to invoke a (static) method on this class: FooClass.MyMethod();

显然,我需要找到通过反射一个参考类,但怎么样?

Obviously, I need to find a reference to the class via reflection, but how?

推荐答案

您将要使用 Type.GetType 方法。

You will want to use the Type.GetType method.

下面是一个很简单的例子:

Here is a very simple example:

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");
    }
}

我说的简单的,因为它是很容易找到一种这样,它是内部相同的组件。请参阅<一个href=\"http://stackoverflow.com/questions/1044455/c-reflection-how-to-get-class-reference-from-string/1044472#1044472\">Jon's回答有关更详尽的解释,你需要了解什么。一旦你已经检索到的类型我的例子显示了如何调用该方法。

I say simple because it is very easy to find a type this way that is internal to the same assembly. Please see Jon's answer for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.

这篇关于C#反思:如何从字符串获取类引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆