I would like to be able to store various static methods in a List and later look them up and dynamically call them.
Each of the static methods has different numbers of a
You can create a list of delegate-instances, using an appropriate delegate-type for each method.
var list = new List<dynamic>
{
new Func<int, int, int> (X),
new Func<int, int, string, string> (Y)
};
dynamic result = list[0](1, 2); // like X(1, 2)
dynamic result2 = list[1](5, 10, "hello") // like Y(5, 10, "hello")
List<dynamic> list = new List<dynamic>();
Action<int, int> myFunc = (int x, int y) => Console.WriteLine("{0}, {1}", x, y);
Action<int, int> myFunc2 = (int x, int y) => Console.WriteLine("{0}, {1}", x, y);
list.Add(myFunc);
list.Add(myFunc2);
(list[0])(5, 6);
You actually don't need the power of dynamic
here, you can do with simple List<object>
:
class Program
{
static int f(int x) { return x + 1; }
static void g(int x, int y) { Console.WriteLine("hallo"); }
static void Main(string[] args)
{
List<object> l = new List<object>();
l.Add((Func<int, int>)f);
l.Add((Action<int, int>)g);
int r = ((Func<int, int>)l[0])(5);
((Action<int, int>)l[1])(0, 0);
}
}
(well, you need a cast, but you need to somehow know the signature of each of the stored methods anyway)