如何调用它的名字来作为参数共享功能它的、名字、参数、功能

2023-09-06 23:52:34 作者:几分曾经.

在一个方法,我想调用哪个名字来作为一个参数,一个共享的功能。

In a method, I want to call a shared function which its name came as a parameter.

例如:

private shared function func1(byval func2 as string)
 'call func2
end function

我怎样才能做到这一点?

How can i do it?

推荐答案

您可以使用反射来寻找类和方法。

You can use reflection to find the class and the method.

实例在C#:

Example in C#:

namespace TestProgram {

  public static class TestClass {

    public static void Test() {
      Console.WriteLine("Success!");
    }

  }

  class Program {

    public static void CallMethod(string name) {
      int pos = name.LastIndexOf('.');
      string className = name.Substring(0, pos);
      string methodName = name.Substring(pos + 1);
      Type.GetType(className).GetMethod(methodName).Invoke(null, null);
    }

    static void Main() {
      CallMethod("TestProgram.TestClass.Test");
    }

  }

}