0

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.

2
  • What are you going to do with this list? If you want to invoke these methods at some point, you'll need to specify the required arguments (which implies that you'll need to know the number and types of arguments to be supplied...). Commented Sep 2, 2015 at 14:17
  • Later I will randomly pick an Operation in opList to be invoked. The actual solution is something like: Random rnd = new Random(); int random = rnd.Next(opList.Count()); opList[random].Invoke(supervisor); Commented Sep 2, 2015 at 14:25

1 Answer 1

2

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>.

Sign up to request clarification or add additional context in comments.

3 Comments

e.g., opList[0](new ExampleClass())
That solutions works, but not for my case, because I only want in my opList certain methods of the class Operations
Could you formulate a criteria to search for the methods? Actually, in this case you just need to filter reflected methods, using given criteria.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.