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

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

DDD
DDDOriginal
2025-01-28 05:41:11891browse

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

The dynamic code in the c#executes

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 Solution using the Roslyn script API:

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

Roslyn script API allows you to execute any C#code fragment:

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!

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