Calling a function from a string in C#

2018-12-31 21:36发布

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

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

function hello() { echo 'hello'; }

Is this possible in .Net?

6条回答
泪湿衣
2楼-- · 2018-12-31 22:02

In C#, you can create delegates as function pointers. Check out the following MSDN article for information on usage: 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.
查看更多
看风景的人
3楼-- · 2018-12-31 22:11
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楼-- · 2018-12-31 22:12

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
查看更多
笑指拈花
5楼-- · 2018-12-31 22:13

In Fact I am working on Windows Workflow 4.5 and I got to find a way to pass a delegate from a statemachine to a method with no success. The only way I got to find was to pass a string with the name of the method I wanted to pass as delegate and to convert the string to a delegate inside the method. Very nice answer. Thanks. Check this link https://msdn.microsoft.com/en-us/library/53cz7sc6(v=vs.110).aspx

查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 22:22

A slight tangent -- if you want to parse and evaluate an entire expression string which contains (nested!) functions, consider NCalc (http://ncalc.codeplex.com/ and nuget)

Ex. slightly modified from the project documentation:

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

And within the EvaluateFunction delegate you would call your existing function.

查看更多
唯独是你
7楼-- · 2018-12-31 22:25

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);
查看更多
登录 后发表回答