Help with calling functions
I have a bunch of functions(F1,F2,...,Fn) and I'm going to be calling them at random.
They're a little too many for me to use branching such as:
if(random == 1)
F1();
else if(random == 2)
F2();
...
Is there any way for me to be able to call a function by using a variable as the function name, something like Fi(); (i being the random number).
My guess is it would have something to do with delegates, but I'm not really familiar with them.
I'm using Visual Studio 2008, C#
Thanks in advance
Use an array of delegates (or, more generally, a Dictionary):
(Google 'Func delegate MSDN')
Basically, Func is a generic delegate class representing a function that takes up to 4 arguments and returns a value:
Func<string> f is string f()
Func<int, string> f is string f(int)
Func<int, int, string> f is string f(int, int)
Func<int, int, int, string> f is string f(int, int, int)
Func<int, int, int, int, string> f is string f(int, int, int, int)
Beyond that you'll need to define your own delegate (or consider refactoring the function to have fewer arguments).
using System;public class Program{ string fn1() { return "fn1"; } string fn2() { return "fn2"; } public static void Main() { Func<string>[] funcs = {fn1, fn2}; int i = getMagicNumber(); funcs(); }};
(Google 'Func delegate MSDN')
Basically, Func is a generic delegate class representing a function that takes up to 4 arguments and returns a value:
Func<string> f is string f()
Func<int, string> f is string f(int)
Func<int, int, string> f is string f(int, int)
Func<int, int, int, string> f is string f(int, int, int)
Func<int, int, int, int, string> f is string f(int, int, int, int)
Beyond that you'll need to define your own delegate (or consider refactoring the function to have fewer arguments).
Quote:Original post by Z3R0Bit
Is it possible not to return anything using Func<>?
Annoyingly, not as far as I'm aware. You'll need an Action delegate for that.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement