cmptrer
cmptrer

Reputation: 1449

Calling methods with same signature dynamically

Lets say I have a class like this:

class SomeClass
{

public void ActionFunction()
{
}

public void Do1(int num) {...}

public void Do2(int num) {...}

etc.
}

In ActionFunction I want to read in strings and then call any of the Do's (Do1, Do2, etc.). Since all the functions have the same signature I was thinking this was a job for Delegates. But you can't pass in the string name of a function to delegates, and I'm trying to avoid having a giant switch to figure out which one to call.

I realize I can use reflection for this, but am trying to avoid this due to the performance reasons.

Upvotes: 1

Views: 165

Answers (3)

jbtule
jbtule

Reputation: 31799

If you are using .net 4.0, the opensource framework ImpromptuInterface can use the dlr to call your actions based on a name 4x faster than reflection.

Impromptu.InvokeMemberAction(target, actionName, num);

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564641

You can always maintain a dictionary, internally, and call based on that. You could even use reflection to load the dictionary values, since this would be a one-time, up front cost, and calling would be quick.

private Dictionary<string, Action<int>> doMethods = new Dictionary<string, Action<int>>();
public SomeClass()
{
    Type t = typeof(SomeClass);
    var methods = t.GetMethods().Where(m => m.Name.StartsWith("Do"));

    foreach(var method in methods)
         doMethods.Add(method.Name, (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), this, method, true));
}

public void ActionFunction(string name, int num)
{
    this.doMethods[name](num);
}

Upvotes: 2

anthonyvd
anthonyvd

Reputation: 7590

I'd make a dictionary of <string, Func<int>> where the key is the string and the value is a delegate of the method to call. Then you do something like dict["string"].Value.Invoke()

Upvotes: 1

Related Questions