Llamar a una función desde una cadena en C#


Sé que en php puedes hacer una llamada como:

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

function hello() { echo 'hello'; }

¿Es esto posible en. Net?

Author: Jeremy Boyd, 2009-02-12

6 answers

Sí. Puedes usar la reflexión. Algo como esto:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
 223
Author: ottobar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-12 04:59:14

Puede invocar métodos de una instancia de clase usando reflexión, haciendo una invocación de método dinámico:

Supongamos que tiene un método llamado hello en una instancia real (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);
 61
Author: CMS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-12 04:57:56
class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(MyReflectionClass);
            MethodInfo method = type.GetMethod("MyMethod");
            MyReflectionClass c = new MyReflectionClass();
            string result = (string)method.Invoke(c, null);
            Console.WriteLine(result);

        }
    }

    public class MyReflectionClass
    {
        public string MyMethod()
        {
            return DateTime.Now.ToString();
        }
    }
 34
Author: BFree,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-12 04:57:39

Una ligera tangente if si desea analizar y evaluar una cadena de expresión completa que contiene (anidado!) funciones, considere NCalc ( http://ncalc.codeplex.com / y nuget)

Ex. ligeramente modificado de la documentación del proyecto:

// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);

// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
        if (name == "MyFunction")
            args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
    };

// confirm it worked
Debug.Assert(19 == e.Evaluate());

Y dentro del delegado EvaluateFunction llamarías a tu función existente.

 0
Author: drzaus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-05 15:58:12

De hecho, estoy trabajando en Windows Workflow 4.5 y tengo que encontrar una manera de pasar un delegado de una máquina de estado a un método sin éxito. La única manera que pude encontrar fue pasar una cadena con el nombre del método que quería pasar como delegado y convertir la cadena a un delegado dentro del método. Muy buena respuesta. Gracias. Compruebe este enlace https://msdn.microsoft.com/en-us/library/53cz7sc6 (v=vs.110). aspx

 0
Author: Antonio Leite,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-03 18:26:49

En C#, puede crear delegados como punteros de función. Consulte el siguiente artículo de MSDN para obtener información sobre el uso: http://msdn.microsoft.com/en-us/library/ms173171 (VS.80).aspx

    public static void hello()
    {
        Console.Write("hello world");
    }

   /* code snipped */

    public delegate void functionPointer();

    functionPointer foo = hello;
    foo();  // Writes hello world to the console.
 -7
Author: regex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-25 13:41:44