如何在.NET中动态调用类的方法?

时间:2009-07-13 15:38:19

标签: c# reflection

如何将类和方法名称作为 strings 传递并调用该类的方法?

void caller(string myclass, string mymethod){
    // call myclass.mymethod();
}

由于

3 个答案:

答案 0 :(得分:30)

您需要使用reflection

这是一个简单的例子:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        caller("Foo", "Bar");
    }

    static void caller(String myclass, String mymethod)
    {
        // Get a type from the string 
        Type type = Type.GetType(myclass);
        // Create an instance of that type
        Object obj = Activator.CreateInstance(type);
        // Retrieve the method you are looking for
        MethodInfo methodInfo = type.GetMethod(mymethod);
        // Invoke the method on the instance we created above
        methodInfo.Invoke(obj, null);
    }
}

class Foo
{
    public void Bar()
    {
        Console.WriteLine("Bar");
    }
}

现在这是一个非常简单的例子,没有错误检查,也忽略了更大的问题,比如如果类型存在于另一个程序集中该怎么办,但我认为这应该让你在正确的轨道上。

答案 1 :(得分:8)

这样的事情:

public object InvokeByName(string typeName, string methodName)
{
    Type callType = Type.GetType(typeName);

    return callType.InvokeMember(methodName, 
                    BindingFlags.InvokeMethod | BindingFlags.Public, 
                    null, null, null);
}

您应该根据要调用的方法修改绑定标志,并检查msdn中的Type.InvokeMember方法以确定您真正需要的内容。

答案 2 :(得分:-3)

你这样做的原因是什么?您很可能无需反思即可完成此操作,包括动态装配加载。