Tiago Neto
Tiago Neto

Reputation: 379

Using Reflection to create automatically a List of Delegates

I have a Class called Operations.cs with some method. I want to create a List of Delegates to pick a method randomly. Right now I have the following working solution:

public delegate void Delmethod(ExampleClass supervisor);
public static Operations op = new Operations();
public List<Delmethod> opList = new List<Delmethod>();

opList.Add(op.OpOne);
opList.Add(op.OpTwo);
opList.Add(op.OpThree);
opList.Add(op.OpFour);
opList.Add(op.OpFive);
opList.Add(op.OpSix);
opList.Add(op.OpSeven);

But what I really want is generate the List opList automatically in the case I add a new method in the Operations.cs. I was trying to use reflection in an atempt to solve my problem as follows:

List<MethodInfo> listMethods = new List<MethodInfo>(op.GetType().GetMethods().ToList());

foreach (MethodInfo meth in listMethods)
{
   opList.Add(meth);
}

I believe that this doesn't work because I'm making a confusion about the meaning of delegate, but I'm out of ideas.

Upvotes: 0

Views: 139

Answers (1)

Dennis
Dennis

Reputation: 37780

You have to make a delegate from particular method info. Assuming, that Operations has only public instance methds with the same signature, the code will look like this:

public static Operations op = new Operations();
public List<Action<ExampleClass>> opList = new List<Action<ExampleClass>>();

oplist.AddRange(op
    .GetType()
    .GetMethods()
    .Select(methodInfo => (Action<ExampleClass>)Delegate.CreateDelegate(typeof(Action<ExampleClass>), op, methodInfo)));

Note, that you don't need to declare Delmethod, since there is Action<T>.

Upvotes: 2

Related Questions