Dynamic evaluation of C# expression at runtime
In software development, sometimes it is necessary to dynamically evaluate the C# expression at runtime. This article will provide a modern and efficient solution.
Traditional methods usually use
to compile and execute expressions, but this method is outdated and no longer meets the best practice of modern C#.
CSharpCodeProvider
The better method is to use the Roslyn script API. The API provides a engine dedicated to dynamically evaluating the C# script and expression, which simplifies the expression evaluation process:
This example evaluate the expression "1 3", and assign the results to
<code class="language-csharp">using Microsoft.CodeAnalysis.CSharp.Scripting; var result = CSharpScript.EvaluateAsync("1 + 3").Result;</code>
result
<code class="language-csharp">var now = CSharpScript.EvaluateAsync<string>("System.DateTime.Now.ToString()").Result;</code>
The above is the detailed content of How Can I Dynamically Evaluate C# Expressions at Runtime Using Roslyn?. For more information, please follow other related articles on the PHP Chinese website!