Home >Backend Development >C++ >How Can I Achieve Dynamic Code Evaluation in C# Like JavaScript's `eval()`?
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
eval()
sample code
To evaluate simple expressions, use
Method:For more complicated code, you can use
Method:
EvaluateAsync()
<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()
<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!