Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call methods using names in C#

Tags:

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.

like image 970
Chris Avatar asked Jun 24 '11 14:06

Chris


People also ask

How can I call a function given its name as a string in C?

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.

What is __ function __ in C?

(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.

Can we have multiple names for functions in C?

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.


1 Answers

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()); } 
like image 69
Igby Largeman Avatar answered Sep 19 '22 17:09

Igby Largeman