How to pass a method name to another method and call it through a delegate variable?

I have a method that contains a delegate variable that points to another class. I want to call a method in this class through this delegate, but pass the name of the method as a string to the method containing the delegate.

How can I do that? Using reflection? Func<T>?

Edit:

Now I understand that reflection may not be the best solution.

This is what I have:

private static void MethodContainingDelegate(string methodNameInOtherClassAsString)
{
        _listOfSub.ForEach(delegate(Callback callback)
        {
            //Here the first works, but I want the method to be general and   
            //  therefore pass the method name as a string, not specfify it. 
            callback.MethodNameInOtherClass(); 
            //This below is what I am trying to get to work. 
             callback.MethodNameInOtherClassAsString();                  
          }
     });
}

So basically, I'm looking for a way to make the callback delegate β€œrecognize” that my NameInOtherClassAsString method is actually a method to execute in another class.

Thank!

+3
source share
3 answers

It is very simple:

public delegate void DelegateTypeWithParam(object param);
public delegate void DelegateTypeWithoutParam();

public void MethodWithCallbackParam(DelegateTypeWithParam callback, DelegateTypeWithoutParam callback2)
{
    callback(new object());
    Console.WriteLine(callback.Method.Name);
    callback2();
    Console.WriteLine(callback2.Method.Name);
}

// must conform to the delegate spec
public void MethodWithParam(object param) { }
public void MethodWithoutParam() { }

public void PassCallback()
{
   MethodWithCallbackParam(MethodWithParam, MethodWithoutParam);
}

, . - .

, . , Method .

+3

- :

var mi = typeof(Foo).GetMethods().Single(x => x.Name == "Bar");
mi.Invoke(foo, null);

Foo - , Bar - , . , . .

+2

, :

var methodInfo = myObject.GetType().GetMethod(myString); //<- this can throw or return null
methodInfo.Invoke(myObject, new object[n]{parm1, pram2,...paramn});

, , , , GetMethod.

0

All Articles