How to Call method using its name?

后端 未结 3 475
执笔经年
执笔经年 2021-01-12 09:15

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();
相关标签:
3条回答
  • 2021-01-12 09:33

    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.

    0 讨论(0)
  • 2021-01-12 09:39

    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.

    0 讨论(0)
  • 2021-01-12 09:43
    object obj;
    var dyn = (dynamic) obj;
    dyn.method();
    
    0 讨论(0)
提交回复
热议问题