Use Roslyn to dynamically evaluate C#expression
In the construction of data -driven applications or running the time code generation, dynamic evaluation C#expression is often required. This article will demonstrate how to use the Microsoft Roslyn compiler platform to achieve this goal.
Use the script API
Roslyn's script API provides a convenient way to evaluate expression and code fragments. The specific steps are as follows:
Install the Nuget package:
Add
Evaluation expression: Microsoft.CodeAnalysis.CSharp.Scripting
Use the
Specify the result type: CSharpScript.EvaluateAsync
In order to specify the type of evaluated expression, the generic
<code class="language-csharp"> var result = CSharpScript.EvaluateAsync("1 + 3").Result;</code>
Example usage CSharpScript.EvaluateAsync<T>
<code class="language-csharp"> var now = CSharpScript.EvaluateAsync<string>("System.DateTime.Now.ToString()").Result;</code>
Script API supports many senior characteristics, for example:
The parameters of the passing code passed by the evaluation code
<code class="language-csharp">using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; // 评估 "1 + 3" var result = CSharpScript.EvaluateAsync("1 + 3").Result; Console.WriteLine(result); // 输出 4 // 评估 "System.DateTime.Now.ToString()" var now = CSharpScript.EvaluateAsync<string>("System.DateTime.Now.ToString()").Result; Console.WriteLine(now); // 输出当前日期时间</code>
Provide a reference to the assembly Specify the name space and target framework
For more details, please refer to the Roslyn script API document:
The above is the detailed content of How Can I Dynamically Evaluate C# Expressions Using Roslyn?. For more information, please follow other related articles on the PHP Chinese website!