简体   繁体   中英

How to execute a method in class with C# ScriptEngine

How can I get the result of this source

var src = @"public class Test
{
    public IList<string> CallMe(int count = 10)
    {
        return Enumerable.Range(0, count).Select(x => $""Number-{x}"").ToList();
    }
}";

by Roslyn ScriptEngine in C#?

How can I do this?

object result = await CSharpScript.EvaluateAsync("new Test().CallMe(20)");

The one of way to do that is use continuation from Roslyn Scripting that keeps the previous state of execution:

var src = @"public class Test
{
    public IList<string> CallMe(int count = 10)
    {
        return Enumerable.Range(0, count).Select(x => $""Number-{x}"").ToList();
    }
}";

var options = ScriptOptions.Default
    .AddReferences("mscorlib", "System.Core") // assume that it's run under .netframework
    .AddImports("System", "System.Linq", "System.Collections.Generic");

var list = CSharpScript.RunAsync(src, options).Result
                       .ContinueWithAsync<IList<string>>("new Test().CallMe(20)").Result.ReturnValue;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM