Pass object instance to Roslyn ScriptEngine

后端 未结 2 782
栀梦
栀梦 2021-01-05 00:17

I\'m looking for a C# scripting engine, that can interpret blocks of C# code, while maintaing a context. For example, if enter to it: var a = 1; , and then

2条回答
  •  被撕碎了的回忆
    2021-01-05 00:40

    The answer was found in a link commented by @Herman.

    As it turn out, Roslyn ScriptEngine/Session supports a concept of Host Object. In order to use it, define a class of your choise, and pass it upon session creation. Doing so, makes all public member of that host object, available to context inside the session:

    public class MyHostObject
    {
        public List list_of_ints;
        public int an_int = 23;
    }
    
    var hostObject = new MyHostObject();
    hostObject.list_of_ints = new List();
    hostObject.list_of_ints.Add(2);
    var engine = new ScriptEngine(new[] { hostObject.GetType().Assembly.Location });
    
    // passing reference to hostObject upon session creation
    var session = Session.Create(hostObject);
    
    // prints `24` to console
    engine.Execute(@"System.Console.WriteLine(an_int + list_of_ints.Count);", 
                   session); 
    

提交回复
热议问题