APISampleUnitTestsCS.FAQ.ShareStateBetweenHostAndScript C# (CSharp) Метод

ShareStateBetweenHostAndScript() приватный Метод

private ShareStateBetweenHostAndScript ( ) : void
Результат void
        public void ShareStateBetweenHostAndScript()
        {
            // The host object.
            var state = new State();

            // Note that free identifiers in the script code bind to public members of the host object.
            var script1 = @"
            using System;
            using System.Linq;

            int i = 1; int j = 2;
            var array = new[] {i, j};
            var query = array.Where(a => a > 0).Select(a => a + 1);

            SharedValue += query.First() + query.Last();
            SharedValue"; // Script simply returns updated value of the shared state.

            // Create a new ScriptEngine.
            var engine = new ScriptEngine();
            engine.AddReference("System.Core");

            // Reference to current assembly is required so that script can find the host object.
            engine.AddReference(typeof(State).Assembly);

            // Create a Session that holds the host object that is used to share state between host and script.
            var session = engine.CreateSession(state);

            // Execute above script once under the session so that variables i and j are declared.
            session.Execute(script1);

            // Note that free identifiers in the script code bind to public members of the host object.
            var script2 = @"
            SharedValue += i + j;
            SharedValue"; // Script simply returns updated value of the shared state.
            var script3 = "i = 3; j = 4;";

            // Execute other scripts under the above session.
            // Note that script execution remembers variables declared previously in the session and
            // also sees changes in the shared session state.
            state.SharedValue = 3;
            int result = session.Execute<int>(script2);
            Assert.AreEqual(6, result);
            Assert.AreEqual(6, state.SharedValue);

            state.SharedValue = 4;
            session.Execute(script3);
            result = session.Execute<int>(script2);
            Assert.AreEqual(11, result);
            Assert.AreEqual(11, state.SharedValue);
        }