2

I have one of several methods (Strategy1, Strategy2), ... that need to be called depending on an id that is passed in.

Is it possible to save a method name in a db and call that method using the stored name?

Currently I have the StrategyID saved as an enum and use a switch statement matching passed in ID's with the appropriate strategy enum. I don't like this solution as you need to keep the enum synchronised with the Strategies db table.

What I want to do is take the switch out of the front end and put it in the db. So essentially I can make a db call (FetchStrategiesToRun) and the appropriate list of Strategies will be returned and I can loop through them calling the method directly.

If so, how. And if so, is there any reason I'd not be wanting to do this?

Dave Tapson
  • 810
  • 1
  • 9
  • 22

2 Answers2

3

This seems similar to Dynamically invoking any function by passing function name as string

// All error checking omitted. In particular, check the results
// of Type.GetType, and make sure you call it with a fully qualified
// type name, including the assembly if it's not in mscorlib or
// the current assembly. The method has to be a public instance
// method with no parameters. (Use BindingFlags with GetMethod
// to change this.)
public void Invoke(string typeName, string methodName)
{
    Type type = Type.GetType(typeName);
    object instance = Activator.CreateInstance(type);
    MethodInfo method = type.GetMethod(methodName);
    method.Invoke(instance, null);
}

or

public void Invoke<T>(string methodName) where T : new()
{
    T instance = new T();
    MethodInfo method = typeof(T).GetMethod(methodName);
    method.Invoke(instance, null);
}

More info here, using System.Reflection;

http://www.dotnetperls.com/getmethod

using System;
using System.Reflection;

static class Methods
{
    public static void Inform(string parameter)
    {
    Console.WriteLine("Inform:parameter={0}", parameter);
    }
}

class Program
{
    static void Main()
    {
    // Name of the method we want to call.
    string name = "Inform";

    // Call it with each of these parameters.
    string[] parameters = { "Sam", "Perls" };

    // Get MethodInfo.
    Type type = typeof(Methods);
    MethodInfo info = type.GetMethod(name);

    // Loop over parameters.
    foreach (string parameter in parameters)
    {
        info.Invoke(null, new object[] { parameter });
    }
    }
}
Community
  • 1
  • 1
user1666620
  • 4,800
  • 18
  • 27
0

You can do this using reflection Invoke the method by its name. Example of how to do that is present in the folowing link click here

Community
  • 1
  • 1
kishore V M
  • 818
  • 6
  • 13