Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list of methods then execute them?

Tags:

I'm trying to create a list that contains methods, and after I add some methods I want to execute them, is this possible?

I tried something like this:

List<object> methods = new List<object>(); 

Then:

methods.Add(Move()); 

But When I add, the program will call the methods, for example, in this case it called for Move();

like image 517
user3491915 Avatar asked May 02 '14 22:05

user3491915


People also ask

How to create a list of methods in c#?

List<Action> functions = new List<Action>(); functions. Add(Move); functions. Add(() => MoveTo(1, 5)); foreach (Action func in functions) func();

Can you make a list of methods in Python?

Python has a set of built-in methods that you can use on lists/arrays. Note: Python does not have built-in support for Arrays, but Python Lists can be used instead. Learn more about lists in our Python Lists Tutorial.


1 Answers

This is a great use case for the Action generic delegate.

List<Action> functions = new List<Action>(); functions.Add(Move);  foreach (Action func in functions)    func(); 

If you need parameters, I would use lambdas to abstract them away:

List<Action> functions = new List<Action>(); functions.Add(Move); functions.Add(() => MoveTo(1, 5));  foreach (Action func in functions)    func(); 

A delegate is akin to function pointers from C++, it holds what a function "is" (not a return value like in your example) so you can call it just like a regular function. The Action generic delegate takes no parameters and returns nothing, so it is ideal for generic "call these functions".

MSDN for Action: Action Delegate

For more on the different types of delegates provided by.NET: https://stackoverflow.com/a/567223/1783619

like image 168
BradleyDotNET Avatar answered Sep 20 '22 14:09

BradleyDotNET