views:

40

answers:

2

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

For example:

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

How can i do it?

+1  A: 

You could use reflection:

class Program
{
    static void Main(string[] args)
    {
        new Program().Foo("Bar");
    }

    public void Foo(string funcName)
    {
        GetType().GetMethod(funcName).Invoke(this, null);
    }

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

Or if it is a static method:

typeof(TypeThatContainsTheStaticMethod)
    .GetMethod(funcName)
    .Invoke(null, null);
Darin Dimitrov
+1  A: 

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

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

  }

}
Guffa