开发者

How to Call method using its name? [duplicate]

开发者 https://www.devze.com 2023-04-03 12:17 出处:网络
This question already has answers here: Calling a function from a string in C# (5 answers) Closed 2 years ago.
This question already has answers here: Calling a function from a string in C# (5 answers) Closed 2 years ago. 开发者_运维技巧

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

object obj;
obj.method();


Given a method MethodName with the signature void MethodName(int num), it would be done something like:

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

Hope this helps.


In addition to reflection you may also want to look at dynamic invocation; which is latebound (i.e. at runtime as opposed to compile time) dispatch of method invocations.


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

精彩评论

暂无评论...
验证码 换一张
取 消