Calling a function from a string in C#

前端 未结 6 1579
别那么骄傲
别那么骄傲 2020-11-22 11:41

I know in php you are able to make a call like:

$function_name = \'hello\';
$function_name();

function hello() { echo \'hello\'; }

Is this

6条回答
  •  温柔的废话
    2020-11-22 12:38

    You can invoke methods of a class instance using reflection, doing a dynamic method invocation:

    Suppose that you have a method called hello in a the actual instance (this):

    string methodName = "hello";
    
    //Get the method information using the method info class
     MethodInfo mi = this.GetType().GetMethod(methodName);
    
    //Invoke the method
    // (null- no parameter for the method call
    // or you can pass the array of parameters...)
    mi.Invoke(this, null);
    

提交回复
热议问题