Home > OS >  How to make a delegated list of anonymous function calls with different inputs? c#
How to make a delegated list of anonymous function calls with different inputs? c#

Time:04-28

I want to make a list of delegated, anonymous function calls so I can 'save' them to actually call later. Although I can guarantee that none of the functions will have a return value, they don't all take in the same types of inputs. I think it would look something like this, but it doesn't even let me compile the list. How can I fix this?

using System;
public class Program
    {
        public static void Main()
        {
            List<delegate> delList = new List<delegate>();
            delList.Add(() => Test("y"));
            delList.Add(() => Test("z"));
            delList.Add(() => Test2(1));
            foreach(delegate d in delList){
                d.Invoke();
            }
        }
        public void Test(string x){
            Debug.Log("Test "   x);
        }
        
        public void Test2(int x){
            Debug.Log("Test2 "   (int)x);   
        }
    }

CodePudding user response:

Something like this?

var delList = new List<Action>();

delList.Add(() => Test("y"));
delList.Add(() => Test("z"));
delList.Add(() => Test2(1));

foreach (Action action in delList)
{
    action();
}
  • Related