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

pis*_*hio 13 c# reflection

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

喜欢

void caller(string myclass, string mymethod){
    // call myclass.mymethod();
}
Run Code Online (Sandbox Code Playgroud)

谢谢

And*_*are 32

你会想要使用反射.

这是一个简单的例子:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 那是因为包含 myclass 的程序集尚未加载到 appdomain 中。您必须从调用者那里获取程序集名称,然后执行 Assembly.LoadFrom 或众多变体之一来首先加载程序集。 (2认同)

Ken*_* K. 9

像这样的东西:

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

    return callType.InvokeMember(methodName, 
                    BindingFlags.InvokeMethod | BindingFlags.Public, 
                    null, null, null);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 你是对的,我很抱歉。编辑添加不能省略的方法参数(C# 4.0 where art thou):) (2认同)