How to call a method using its name?

I have an object with some methods, and I want to call a method using the method name only as a string.

object obj; obj.method(); 
+6
source share
3 answers

Given a MethodName method with a signature void MethodName(int num) , this will be done something like this:

  MethodInfo method = obj.GetType().GetMethod("MethodName", BindingFlags.Public|BindingFlags.Instance) method.Invoke(obj, 4) // void method 

Hope this helps.

+8
source

In addition to thinking, you can also look at dynamic invocation; which is late (i.e. at runtime, not compile time) of sending method calls.

+2
source
 object obj; var dyn = (dynamic) obj; dyn.method(); 
0
source

Source: https://habr.com/ru/post/896936/


All Articles