Home >Backend Development >C++ >How Can I Achieve Dynamic Code Evaluation in C# Like JavaScript's `eval()`?

How Can I Achieve Dynamic Code Evaluation in C# Like JavaScript's `eval()`?

Barbara Streisand
Barbara StreisandOriginal
2025-01-28 05:51:09418browse

How Can I Achieve Dynamic Code Evaluation in C# Like JavaScript's `eval()`?

Implement the dynamic code execution in C#

This article discusses how to dynamically execute the code in C#, similar to the

function in JavaScript.

eval() Problem description

Suppose you have an integer variable and multiple attributes called "Property1", "Property2", "Property3" and other attributes. According to the value, you want to perform operations on the corresponding "Property

I

" attribute. Use i in JavaScript to easily complete this task, but how to achieve it in C#? i Solution using the Roslyn script API eval()

Roslyn script API provides a solution for dynamic code assessment in C#. It contains a set of classes that allow you to execute the C#code at runtime.

sample code

To evaluate simple expressions, use

Method:

For more complicated code, you can use

Method:

EvaluateAsync()

Then you can call
<code class="language-csharp">// 添加NuGet包 'Microsoft.CodeAnalysis.Scripting'
using Microsoft.CodeAnalysis.CSharp.Scripting;

await CSharpScript.EvaluateAsync("System.Math.Pow(2, 4)"); // 返回16</code>
Continue to execute the code:

RunAsync()

This allows you to dynamically execute the C#code and interact with the generated object.
<code class="language-csharp">var script = await CSharpScript.RunAsync(@"
class MyClass
{ 
    public void Print() => System.Console.WriteLine(1);
}");</code>

The above is the detailed content of How Can I Achieve Dynamic Code Evaluation in C# Like JavaScript's `eval()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn