How can I evaluate a C# expression dynamically?

后端 未结 7 1256
情话喂你
情话喂你 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:15

    If you specifically want to call into code and assemblies in your own project I would advocate using the C# CodeDom CodeProvider.

    Here is a list of the most popular approaches that I am aware of for evaluating string expressions dynamically in C#.

    Microsoft Solutions

    • C# CodeDom CodeProvider:
      • See How LINQ used to work and this CodeProject article
    • Roslyn:
      • See this article on Rosly Emit API and this StackOverflow answer
    • DataTable.Compute:
      • See this answer on StackOverflow
    • Webbrowser.Document.InvokeScript
      • See this StackOverflow question
    • DataBinder.Eval
    • ScriptControl
      • See this answer on StackOverflow and this question
    • Executing PowerShell:
      • See this CodeProject article

    Non-Microsoft solutions (not that there is anything wrong with that)

    • Expression evaluation libraries:
      • Flee
      • DynamicExpresso
      • NCalc
      • CodingSeb.ExpressionEvaluator
      • Eval-Expression.NET
    • Javascript interpreter
      • Jint
    • To execute real C#
      • CS-Script
    • Roll your own a language building toolkit like:
      • Irony
      • Jigsaw

提交回复
热议问题