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

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

问题描述

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

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

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

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

我说简单是因为通过这种方式很容易找到同一程序集内部的类型.请参阅乔恩的回答关于您需要了解的内容的更详尽的解释.检索类型后,我的示例将向您展示如何调用该方法.

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天全站免登陆