I have a number of 'jobs' in my application, where each job has a list of methods which it needs to call, along with it's parameters. Essentially a list containing the following object is called:
string Name; List<object> Parameters;
So basically, when a job runs I want to enumerate through this list, and call the relevant methods. For example, if I have a method like the following:
TestMethod(string param1, int param2)
My method object would be like this:
Name = TestMethod Parameters = "astring", 3
Is it possible to do this? I imagine reflection will be the key here.
C does not support this kind of operation (languages that have reflection would). The best you're going to be able to do is to create a lookup table from function names to function pointers and use that to figure out what function to call. Or you could use a switch statement.
(C++11) The predefined identifier __func__ is implicitly defined as a string that contains the unqualified and unadorned name of the enclosing function. __func__ is mandated by the C++ standard and is not a Microsoft extension.
Yes , you can't give same name to functions in C as C is not OOP language , the concept of using same function name is called function overloading, which cannot be used in C. Same variable names cannot be given to the variables ,but same name can be given only if the CASE of variable name is different.
Sure, you can do it like this:
public class Test { public void Hello(string s) { Console.WriteLine("hello " + s); } } ... { Test t = new Test(); typeof(Test).GetMethod("Hello").Invoke(t, new[] { "world" }); // alternative if you don't know the type of the object: t.GetType().GetMethod("Hello").Invoke(t, new[] { "world" }); }
The second parameter of Invoke() is an array of Object containing all the parameters to pass to your method.
Assuming the methods all belong to the same class, you could have a method of that class something like:
public void InvokeMethod(string methodName, List<object> args) { GetType().GetMethod(methodName).Invoke(this, args.ToArray()); }
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