How can I evaluate C# code dynamically?

后端 未结 16 1936
[愿得一人]
[愿得一人] 2020-11-22 03:37

I can do an eval(\"something()\"); to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?

An example of what I

16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:24

    Using the Roslyn scripting API (more samples here):

    // add NuGet package 'Microsoft.CodeAnalysis.Scripting'
    using Microsoft.CodeAnalysis.CSharp.Scripting;
    
    await CSharpScript.EvaluateAsync("System.Math.Pow(2, 4)") // returns 16
    

    You can also run any piece of code:

    var script = await CSharpScript.RunAsync(@"
                    class MyClass
                    { 
                        public void Print() => System.Console.WriteLine(1);
                    }")
    

    And reference the code that was generated in previous runs:

    await script.ContinueWithAsync("new MyClass().Print();");
    

提交回复
热议问题