How can I evaluate a C# expression dynamically?

后端 未结 7 1223
情话喂你
情话喂你 2020-11-22 07:22

I would like to do the equivalent of:

object result = Eval(\"1 + 3\");
string now    = Eval(\"System.DateTime.Now().ToString()\") as string

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 08:03

    Old topic, but considering this is one of the first threads showing up when googling, here is an updated solution.

    You can use Roslyn's new Scripting API to evaluate expressions.

    If you are using NuGet, just add a dependency to Microsoft.CodeAnalysis.CSharp.Scripting. To evaluate the examples you provided, it is as simple as:

    var result = CSharpScript.EvaluateAsync("1 + 3").Result;
    

    This obviously does not make use of the scripting engine's async capabilities.

    You can also specify the evaluated result type as you intended:

    var now = CSharpScript.EvaluateAsync("System.DateTime.Now.ToString()").Result;
    

    To evaluate more advanced code snippets, pass parameters, provide references, namespaces and whatnot, check the wiki linked above.

提交回复
热议问题