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

Я знаю, что в php вы можете позвонить:

$function_name = 'hello'; $function_name(); function hello() { echo 'hello'; } 

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

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

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

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

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

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

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

 // the expression to evaluate, eg 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 вы бы назвали вашу существующую функцию.

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

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