Home >Backend Development >C++ >How Can I Achieve Dynamic Code Execution in C# Like JavaScript's eval()?
Similar to the
function in JavaScript, C#can use the Roslyn script API to implement the dynamic code. This API allows you to dynamically compile and execute the C#code at runtime.
eval()
Example:
Suppose you have an integer variable and multiple attributes such as "Property1", "Property2", "Property3". You want to perform operations on the "Property
I" attribute according to the i
value. i
This example dynamically loads the assembly and access the attribute according to the value.
<code class="language-csharp">// 添加NuGet包 'Microsoft.CodeAnalysis.Scripting' using Microsoft.CodeAnalysis.CSharp.Scripting; await CSharpScript.EvaluateAsync($"System.Reflection.Assembly.LoadFrom(\"{new FileInfo(\"your-assembly-to-load.dll\").FullName}\")"); await CSharpScript.RunAsync($"var propertyValue = typeof(YourType).GetProperty(\"Property{i}\").GetValue(yourTypeInstance);");</code>Other functions:
i
You can also quote the previously compiled code:
The above is the detailed content of How Can I Achieve Dynamic Code Execution in C# Like JavaScript's eval()?. For more information, please follow other related articles on the PHP Chinese website!