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 args, types and return values
static int X(int,int)....
static string Y(int,int,string)
I'd like to have a List that I can add them all to:
List<dynamic> list
list.Add(X);
list.Add(Y);
and later:
dynamic result = list[0](1,2);
dynamic result2 = list[1](5,10,"hello")
How to do this in C# 4?
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")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With