Подтвердить что ты не робот

Вызов функции из строки в С#

Я знаю, что в php вы можете сделать такой вызов:

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

function hello() { echo 'hello'; }

Возможно ли это в .Net?

4b9b3361

Ответ 1

Да. Вы можете использовать отражение. Что-то вроде этого:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

Ответ 2

Вы можете вызывать методы экземпляра класса с использованием отражения, выполняя вызов динамического метода:

Предположим, что у вас есть метод, называемый hello в фактическом экземпляре (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);

Ответ 3

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();
        }
    }

Ответ 4

Небольшая касательная - если вы хотите проанализировать и оценить всю строку выражения, содержащую (вложенные!) функции, рассмотрите NCalc (http://ncalc.codeplex.com/ и nuget)

Ex. слегка изменен из проектной документации:

// 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());

И в пределах делегата EvaluateFunction вы бы назвали вашу существующую функцию.

Ответ 5

В самом деле, я работаю над Windows Workflow 4.5, и мне нужно найти способ передать делегата из statemachine в метод без успеха. Единственный способ, которым я должен был найти, - передать строку с именем метода, который я хотел передать как делегат, и преобразовать строку в делегат внутри метода. Очень хороший ответ. Благодарю. Проверьте эту ссылку https://msdn.microsoft.com/en-us/library/53cz7sc6(v=vs.110).aspx

Ответ 6

В С# вы можете создавать делегаты в качестве указателей на функции. Ознакомьтесь с следующей статьей MSDN для получения информации об использовании: 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.